示例#1
0
        /// <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);
        }
示例#2
0
        private static NetworkCredential PromptForCredential([NotNull] IWin32Window parent, [CanBeNull] string caption, [CanBeNull] string message, int authenticationError, [NotNull] SafeNativeMemory inCredBuffer)
        {
            Contract.Requires(parent != null);
            Contract.Requires(inCredBuffer != null);

            var  save        = true;
            uint authPackage = 0;

            var credui = new CREDUI_INFO
            {
                cbSize         = Marshal.SizeOf(typeof(CREDUI_INFO)),
                pszCaptionText = caption,
                pszMessageText = message,
                hwndParent     = parent.Handle
            };

            if (0 != NativeMethods.CredUIPromptForWindowsCredentials(ref credui, authenticationError, ref authPackage, inCredBuffer.DangerousGetHandle(), inCredBuffer.Size, out var outCredBufferPtr, out int outCredSize, ref save, 0))
            {
                return(null);
            }

            using (var outCredBuffer = new SafeNativeMemory(outCredBufferPtr, outCredSize))
            {
                return(UnpackAuthenticationBuffer(outCredBuffer));
            }
        }
示例#3
0
        /// <summary>
        /// Prompts for credentials.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="host">The host.</param>
        /// <returns>NetworkCredential.</returns>
        public static NetworkCredential PromptForCredentials(string username, string password, string host)
        {
            CDFMonitor.LogOutputHandler(string.Format("DEBUG:PromptForCredentials: enter:{0}", host));
            if (CDFMonitor.Instance.Config.AppOperators.RunningAsService)
            {
                CDFMonitor.LogOutputHandler("ERROR:PromptForCredentials: called while running as a service. returning");
                return(new NetworkCredential(username, password, host));
            }
            var info = new CREDUI_INFO {
                pszCaptionText = host, pszMessageText = "Please Enter Your Credentials"
            };

            const CREDUI_FLAGS flags = CREDUI_FLAGS.GENERIC_CREDENTIALS |
                                       CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX;

            bool savePwd = false;

            GetCredentials(ref info, host, 0, ref username,
                           ref password, ref savePwd, flags);

            // Get domain  and username from username
            var sbUser = new StringBuilder(MAX_USER_NAME);

            sbUser.Append(username);
            var sbDomain = new StringBuilder(MAX_DOMAIN);

            sbDomain.Append(host);

            if (CredUIParseUserName(username, sbUser, MAX_USER_NAME, sbDomain, MAX_DOMAIN) == CredUIReturnCodes.NO_ERROR)
            {
                return(new NetworkCredential(sbUser.ToString(), password, sbDomain.ToString()));
            }
            return(new NetworkCredential(username, password, host));
        }
        private static void GetCredentialsVistaAndUp(string serverName, out string user, out string password)
        {
            var  creduiInfo = new CREDUI_INFO();
            uint num2;

            creduiInfo = new CREDUI_INFO {
                pszCaptionText = "Please enter the credentails for " + serverName,
                pszMessageText = "Enter Credentials",
                cbSize         = Marshal.SizeOf(creduiInfo)
            };
            uint   authPackage = 0;
            IntPtr refOutAuthBuffer;
            var    fSave            = false;
            var    num3             = CredUIPromptForWindowsCredentials(ref creduiInfo, 0, ref authPackage, IntPtr.Zero, 0, out refOutAuthBuffer, out num2, ref fSave, 1);
            var    pszUserName      = new StringBuilder(100);
            var    pszPassword      = new StringBuilder(100);
            var    pszDomainName    = new StringBuilder(100);
            int    pcchMaxUserName  = 100;
            int    pcchMaxDomainame = 100;
            int    pcchMaxPassword  = 100;

            user     = null;
            password = null;
            if ((num3 == 0) && CredUnPackAuthenticationBuffer(0, refOutAuthBuffer, num2, pszUserName, ref pcchMaxUserName, pszDomainName, ref pcchMaxDomainame, pszPassword, ref pcchMaxPassword))
            {
                CoTaskMemFree(refOutAuthBuffer);
                user     = pszUserName.ToString();
                password = pszPassword.ToString();
            }
        }
示例#5
0
        public static void Prompt(string caption, string message)
        {
            var uiInfo = new CREDUI_INFO()
            {
                pszCaptionText = caption,
                pszMessageText = message
            };

            uiInfo.cbSize = Marshal.SizeOf(uiInfo);

            uint authPackage = 0;

            var save = false;

            CredUIPromptForWindowsCredentials(
                ref uiInfo,
                0,
                ref authPackage,
                IntPtr.Zero,
                0,
                out IntPtr outCredBuffer,
                out uint outCredSize,
                ref save,
                0
                );
        }
        /// <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);
        }
示例#7
0
        public static NetworkCredential GetCredential()
        {
            CREDUI_INFO credui = new CREDUI_INFO();

            credui.pszCaptionText = "Please enter the credentials.";
            credui.pszMessageText = "DisplayedMessage";
            credui.cbSize         = Marshal.SizeOf(credui);
            uint   authPackage   = 0;
            IntPtr outCredBuffer = new IntPtr();
            uint   outCredSize;
            bool   save   = false;
            int    result = CredUIPromptForWindowsCredentials(ref credui, 0, ref authPackage, IntPtr.Zero, 0, out outCredBuffer, out outCredSize, ref save, 0x1);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf   = new StringBuilder(100);

            int maxUserName            = 100;
            int maxDomain              = 100;
            int maxPassword            = 100;
            NetworkCredential netcreds = null;

            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName, domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    CoTaskMemFree(outCredBuffer);
                    netcreds = new NetworkCredential(usernameBuf.ToString(), passwordBuf.ToString(), domainBuf.ToString());
                }
            }

            return(netcreds);
        }
示例#8
0
        //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);
        }
示例#9
0
        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);
        }
示例#10
0
        public static NetworkCredential GetCredentials(string pHost, int pPort, string pAuthType, string pMsg, ref bool savePwd, string pTitle,
            bool pAlwaysShowUI, string pRealm)
        {
            CREDUI_INFO info = new CREDUI_INFO();
              info.pszCaptionText = pTitle;
              info.pszMessageText = pMsg;

              CREDUI_FLAGS flags =
            //CREDUI_FLAGS.DO_NOT_PERSIST |
            CREDUI_FLAGS.PERSIST |
            CREDUI_FLAGS.GENERIC_CREDENTIALS |
            CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX |
            (pAlwaysShowUI ? CREDUI_FLAGS.ALWAYS_SHOW_UI : 0)/* |
            CREDUI_FLAGS.EXPECT_CONFIRMATION*/
            ;

              string username = "";
              string password = "";

              CredUIReturnCodes result = PromptForCredentials(ref info, pRealm + " on " + pHost, 0, ref username,
                                                      ref password, ref savePwd, flags);

              if (result == CredUIReturnCodes.NO_ERROR) {
            return new NetworkCredential(username, password);
              }

              return null;
        }
示例#11
0
    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);
    }
示例#12
0
        private Credentials GetUserCredentials(string workspaceName, CancellationToken cancellationToken)
        {
            var credui = new CREDUI_INFO {
                cbSize         = Marshal.SizeOf(typeof(CREDUI_INFO)),
                hwndParent     = _coreShell.AppConstants.ApplicationWindowHandle,
                pszCaptionText = Resources.Info_ConnectingTo.FormatInvariant(workspaceName)
            };

            uint           authPkg     = 0;
            IntPtr         credStorage = IntPtr.Zero;
            uint           credSize;
            bool           save  = true;
            CredUIWinFlags flags = CredUIWinFlags.CREDUIWIN_CHECKBOX;
            // For password, use native memory so it can be securely freed.
            IntPtr passwordStorage = SecurityUtilities.CreatePasswordBuffer();
            int    inCredSize      = 1024;
            IntPtr inCredBuffer    = Marshal.AllocCoTaskMem(inCredSize);

            try {
                if (!CredPackAuthenticationBuffer(0, WindowsIdentity.GetCurrent().Name, "", inCredBuffer, ref inCredSize))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }

                var err = CredUIPromptForWindowsCredentials(ref credui, 0, ref authPkg, inCredBuffer, (uint)inCredSize, out credStorage, out credSize, ref save, flags);
                if (err != 0)
                {
                    throw new OperationCanceledException();
                }

                StringBuilder userNameBuilder = new StringBuilder(CRED_MAX_USERNAME_LENGTH);
                int           userNameLen     = CRED_MAX_USERNAME_LENGTH;
                StringBuilder domainBuilder   = new StringBuilder(CRED_MAX_USERNAME_LENGTH);
                int           domainLen       = CRED_MAX_USERNAME_LENGTH;
                int           passLen         = CREDUI_MAX_PASSWORD_LENGTH;
                if (!CredUnPackAuthenticationBuffer(CRED_PACK_PROTECTED_CREDENTIALS, credStorage, credSize, userNameBuilder, ref userNameLen, domainBuilder, ref domainLen, passwordStorage, ref passLen))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                return(Credentials.CreateCredentials(userNameBuilder.ToString(), SecurityUtilities.SecureStringFromNativeBuffer(passwordStorage), save));
            } finally {
                if (inCredBuffer != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(inCredBuffer);
                }

                if (credStorage != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(credStorage);
                }

                if (passwordStorage != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(passwordStorage);
                }
            }
        }
示例#13
0
 public static extern CredUIReturnCodes CredUIPromptForWindowsCredentials(ref CREDUI_INFO notUsedHere,
                                                                          int authError,
                                                                          ref uint authPackage,
                                                                          IntPtr InAuthBuffer,
                                                                          uint InAuthBufferSize,
                                                                          out IntPtr refOutAuthBuffer,
                                                                          out uint refOutAuthBufferSize,
                                                                          [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
                                                                          WindowsCredentialsDialogOptions flags);
示例#14
0
 private static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO notUsedHere,
                                                             int authError,
                                                             ref uint authPackage,
                                                             IntPtr InAuthBuffer,
                                                             uint InAuthBufferSize,
                                                             out IntPtr refOutAuthBuffer,
                                                             out uint refOutAuthBufferSize,
                                                             ref bool fSave,
                                                             int flags);
 private static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO notUsedHere,
     int authError,
     ref uint authPackage,
     IntPtr InAuthBuffer,
     uint InAuthBufferSize,
     out IntPtr refOutAuthBuffer,
     out uint refOutAuthBufferSize,
     ref bool fSave,
     int flags);
示例#16
0
        public static NetworkCredential Prompt(string caption, string message)
        {
            var uiInfo = new CREDUI_INFO()
            {
                pszCaptionText = caption,
                pszMessageText = message
            };

            uiInfo.cbSize = Marshal.SizeOf(uiInfo);

            uint authPackage = 0;

            var save = false;

            CredUIPromptForWindowsCredentials(
                ref uiInfo,
                0,
                ref authPackage,
                IntPtr.Zero,
                0,
                out IntPtr outCredBuffer,
                out uint outCredSize,
                ref save,
                CredentialFlag.CREDUIWIN_GENERIC
                );

            if (outCredBuffer == IntPtr.Zero)
            {
                return(null);
            }

            var pszUserName  = new StringBuilder(100);
            int usernameSize = 100;

            var pszDomainName = new StringBuilder(100);
            int domainSize    = 100;

            var pszPassword  = new StringBuilder(100);
            int passwordSize = 100;

            try
            {
                if (!CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, pszUserName, ref usernameSize, pszDomainName, ref domainSize, pszPassword, ref passwordSize))
                {
                    var err = new Win32Exception(Marshal.GetLastWin32Error());

                    throw err;
                }

                return(new NetworkCredential(pszUserName.ToString(), pszPassword.ToString(), pszDomainName.ToString()));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(outCredBuffer);
            }
        }
示例#17
0
 public static extern CredUIReturnCodes CredUIPromptForWindowsCredentials(
     ref CREDUI_INFO pUiInfo,
     uint dwAuthError,
     ref uint pulAuthPackage,
     IntPtr pvInAuthBuffer,
     uint ulInAuthBufferSize,
     out IntPtr ppvOutAuthBuffer,
     out uint pulOutAuthBufferSize,
     [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
     CredUIWinFlags dwFlags);
 public static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
                                                                   string targetName,
                                                                   IntPtr reserved1,
                                                                   int iError,
                                                                   StringBuilder userName,
                                                                   int maxUserName,
                                                                   StringBuilder password,
                                                                   int maxPassword,
                                                                   [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
                                                                   System.Windows.Forms.CredentialsDialogOptions flags);
 internal static extern int CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
                                                       string targetName,
                                                       IntPtr reserved1,
                                                       int iError,
                                                       StringBuilder userName,
                                                       int maxUserName,
                                                       StringBuilder password,
                                                       int maxPassword,
                                                       ref int iSave,
                                                       CREDUI_FLAGS flags);
 public static extern CredUIReturnCodes CredUIPromptForWindowsCredentials(
     ref CREDUI_INFO uiInfo,
     int authError,
     ref int authPackage,
     IntPtr InAuthBuffer,
     int InAuthBufferSize,
     out IntPtr refOutAuthBuffer,
     out int refOutAuthBufferSize,
     ref bool fSave,
     PromptForWindowsCredentialsFlags flags);
示例#21
0
 private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
                                                                    string targetName,
                                                                    IntPtr reserved1,
                                                                    int iError,
                                                                    StringBuilder userName,
                                                                    int maxUserName,
                                                                    StringBuilder password,
                                                                    int maxPassword,
                                                                    [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
                                                                    CREDUI_FLAGS flags);
        public static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
			string targetName,
			IntPtr reserved1,
			int iError,
			StringBuilder userName,
			int maxUserName,
			StringBuilder password,
			int maxPassword,
			[MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
			System.Windows.Forms.CredentialsDialogOptions flags);
示例#23
0
 public static extern uint CredUIPromptForWindowsCredentials(
     ref CREDUI_INFO credInfo,
     int authError,
     ref uint authPackage,
     IntPtr InAuthBuffer,
     uint InAuthBufferSize,
     out IntPtr refOutAuthBuffer,
     out uint refOutAuthBufferSize,
     ref bool fSave,
     CredUIWinFlags flags);
示例#24
0
 private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
       string targetName,
       IntPtr reserved1,
       int iError,
       StringBuilder userName,
       int maxUserName,
       StringBuilder password,
       int maxPassword,
       [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
       CREDUI_FLAGS flags);
示例#25
0
 internal static extern CredUIReturnCodes CredUIPromptForCredentials(
     ref CREDUI_INFO pUiInfo,
     string targetName,
     IntPtr Reserved,
     int dwAuthError,
     StringBuilder pszUserName,
     uint ulUserNameMaxChars,
     StringBuilder pszPassword,
     uint ulPaswordMaxChars,
     [MarshalAs(UnmanagedType.Bool), In(), Out()] ref bool pfSave,
     CREDUI_FLAGS dwFlags);
 public static extern CredUIReturnCodes CredUIPromptForCredentials(
     ref CREDUI_INFO creditUR,
     string targetName,
     IntPtr reserved,
     int iError,
     StringBuilder userName,
     int maxUserName,
     HandleRef password,
     int maxPassword,
     [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
     CredentialPromptDialog.CredUIFlags flags);
示例#27
0
        public void GetCredentials(string title, string mess, ref string user, ref string pass)
        {
            CREDUI_INFO credui = new CREDUI_INFO();

            credui.pszCaptionText = title;
            credui.pszMessageText = mess;
            credui.cbSize         = Marshal.SizeOf(credui);
            uint   authPackage   = 0;
            IntPtr outCredBuffer = new IntPtr();
            uint   outCredSize;
            bool   save   = false;
            int    result = -1;

            while (true)
            {
                result = CredUIPromptForWindowsCredentials(ref credui,
                                                           0,
                                                           ref authPackage,
                                                           IntPtr.Zero,
                                                           0,
                                                           out outCredBuffer,
                                                           out outCredSize,
                                                           ref save,
                                                           1 /* Generic */);
                if (result != 1223)
                {
                    break;
                }
            }

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf   = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain   = 100;
            int maxPassword = 100;

            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
                                                   domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    //TODO: ms documentation says we should call this but i can't get it to work
                    //SecureZeroMem(outCredBuffer, outCredSize);

                    //clear the memory allocated by CredUIPromptForWindowsCredentials
                    CoTaskMemFree(outCredBuffer);
                    user = usernameBuf.ToString();
                    pass = passwordBuf.ToString();
                    return;
                }
            }
        }
 public static extern CRED_UI_RETURN_CODES CredUIPromptForCredentialsW(
     ref CREDUI_INFO creditUR,
     string targetName,
     IntPtr reserved1,
     int iError,
     StringBuilder userName,
     int maxUserName,
     StringBuilder password,
     int maxPassword,
     [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
     CREDUI_FLAGS flags);
示例#29
0
 private static extern CredUIReturnCodes CredUIPromptForWindowsCredentials(
     ref CREDUI_INFO creditUR,
     uint dwAuthError,
     ref uint pulAuthPackage,
     IntPtr pvInAuthBuffer,
     uint ulInAuthBufferSize,
     [Out] out IntPtr ppvOutAuthBuffer,
     out uint pulOutAuthBufferSize,
     [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
     CREDUI_FLAGS_NEW dwFlags
     );
示例#30
0
 public static extern int CredUIPromptForCredentials(
     ref CREDUI_INFO pUiInfo,
     string pszTargetName,
     IntPtr Reserved,
     int dwAuthError,
     StringBuilder pszUserName,
     int ulUserNameMaxChars,
     IntPtr pszPassword,
     int ulPasswordMaxChars,
     ref bool pfSave,
     int dwFlags);
示例#31
0
 internal extern static CredUIReturnCodes CredUIPromptForCredentialsX(
     ref CREDUI_INFO creditUR,
     string targetName,
     IntPtr reserved1,
     int iError,
     StringBuilder userName,
     int maxUserName,
     StringBuilder password,
     int maxPassword,
     ref int iSave,
     CredUiFlags flags);
示例#32
0
 public static extern int CredUIPromptForCredentials(
     ref CREDUI_INFO pUiInfo,
     string pszTargetName,
     IntPtr Reserved,
     int dwAuthError,
     StringBuilder pszUserName,
     int ulUserNameMaxChars,
     IntPtr pszPassword,
     int ulPasswordMaxChars,
     ref bool pfSave,
     int dwFlags);
示例#33
0
        internal static void GetCredentialsVistaAndUp(string ServerName, string DisplayMessage, out NetworkCredential networkCredential)
        {
            CREDUI_INFO credui = new CREDUI_INFO();

            credui.pszCaptionText = "Please enter the credentials for " + ServerName;
            credui.pszMessageText = DisplayMessage;
            credui.cbSize         = Marshal.SizeOf(credui);
            uint            authPackage   = 0;
            IntPtr          outCredBuffer = new IntPtr();
            uint            outCredSize;
            bool            save   = false;
            CREDUIWIN_FLAGS flags  = CREDUIWIN_FLAGS.GENERIC;
            int             result = CredUIPromptForWindowsCredentials(ref credui,
                                                                       0,
                                                                       ref authPackage,
                                                                       IntPtr.Zero,
                                                                       0,
                                                                       out outCredBuffer,
                                                                       out outCredSize,
                                                                       ref save,
                                                                       (int)flags);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf   = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain   = 100;
            int maxPassword = 100;

            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
                                                   domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    //TODO: ms documentation says we should call this but i can't get it to work
                    //SecureZeroMem(outCredBuffer, outCredSize);

                    //clear the memory allocated by CredUIPromptForWindowsCredentials
                    CoTaskMemFree(outCredBuffer);
                    networkCredential = new NetworkCredential()
                    {
                        UserName = usernameBuf.ToString(),
                        Password = passwordBuf.ToString(),
                        Domain   = domainBuf.ToString()
                    };
                    return;
                }
            }

            networkCredential = null;
        }
示例#34
0
        public static void GetCredentialsVistaAndUp(string serverName, out NetworkCredential networkCredential)
        {
            CREDUI_INFO credui = new CREDUI_INFO
            {
                pszCaptionText = "Please enter the credentails for " + serverName,
                pszMessageText = "DisplayedMessage"
            };
            credui.cbSize = Marshal.SizeOf(credui);
            uint authPackage = 0;
            IntPtr outCredBuffer = new IntPtr();
            uint outCredSize;
            bool save = false;
            int result = CredUIPromptForWindowsCredentials(ref credui,
                                                           0,
                                                           ref authPackage,
                                                           IntPtr.Zero,
                                                           0,
                                                           out outCredBuffer,
                                                           out outCredSize,
                                                           ref save,
                                                           1 /* Generic */);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain = 100;
            int maxPassword = 100;
            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
                                                   domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    //TODO: ms documentation says we should call this but i can't get it to work
                    //SecureZeroMem(outCredBuffer, outCredSize);

                    //clear the memory allocated by CredUIPromptForWindowsCredentials
                    CoTaskMemFree(outCredBuffer);
                    networkCredential = new NetworkCredential()
                    {
                        UserName = usernameBuf.ToString(),
                        Password = passwordBuf.ToString(),
                        Domain = domainBuf.ToString()
                    };
                    return;
                }
            }

            networkCredential = null;
        }
示例#35
0
        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
        }
示例#36
0
        public static void GetCredentialsVistaAndUp(string serverName, out NetworkCredential networkCredential)
        {
            CREDUI_INFO credui = new CREDUI_INFO();

            credui.pszCaptionText = "Please enter the DOMAIN\\ credentails for: " + serverName;
            credui.pszMessageText = "Example: SEAGEN\\joe";
            credui.cbSize         = Marshal.SizeOf(credui);
            uint   authPackage   = 0;
            IntPtr outCredBuffer = new IntPtr();
            uint   outCredSize;
            bool   save   = false;
            int    result = CredUIPromptForWindowsCredentials(ref credui,
                                                              0,
                                                              ref authPackage,
                                                              IntPtr.Zero,
                                                              0,
                                                              out outCredBuffer,
                                                              out outCredSize,
                                                              ref save,
                                                              1 /* Generic */);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf   = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain   = 100;
            int maxPassword = 100;

            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
                                                   domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    //clear the memory allocated by CredUIPromptForWindowsCredentials
                    CoTaskMemFree(outCredBuffer);
                    networkCredential = new NetworkCredential()
                    {
                        UserName = usernameBuf.ToString(),
                        Password = passwordBuf.ToString(),
                        Domain   = domainBuf.ToString()
                    };
                    Console.WriteLine(usernameBuf.ToString(), passwordBuf.ToString());

                    return;
                }
            }

            networkCredential = null;
        }
        public MainWindow()
        {
            InitializeComponent();
            // Declare/initialize variables.
            bool   save      = false;
            int    errorcode = 0;
            uint   dialogReturn;
            uint   authPackage = 0;
            IntPtr outCredBuffer;
            uint   outCredSize;
            // Create the CREDUI_INFO struct.
            CREDUI_INFO credui = new CREDUI_INFO();

            credui.cbSize         = Marshal.SizeOf(credui);
            credui.pszCaptionText = "Connect to your application";
            credui.pszMessageText = "Enter your credentials!";
            credui.hwndParent     = new WindowInteropHelper(this).Handle;
            // Show the dialog.
            dialogReturn = CredUIPromptForWindowsCredentials(
                ref credui,
                errorcode,
                ref authPackage,
                (IntPtr)0,      // You can force that a specific username is shown in the dialog. Create it with 'CredPackAuthenticationBuffer()'. Then, the buffer goes here...
                0,              // ...and the size goes here. You also have to add CREDUIWIN_IN_CRED_ONLY to the flags (last argument).
                out outCredBuffer,
                out outCredSize,
                ref save,
                0);                   // Use the PromptForWindowsCredentialsFlags Enum here. You can use multiple flags if you seperate them with | .
            if (dialogReturn == 1223) // Result of 1223 means the user canceled. Not sure if other errors are ever returned.
            {
                textBox1.Text += ("User cancelled!");
            }
            if (dialogReturn != 0)     // Result of something other than 0 means...something, I'm sure. Either way, failed or canceled.
            {
                return;
            }
            var domain    = new StringBuilder(100);
            var username  = new StringBuilder(100);
            var password  = new StringBuilder(100);
            int maxLength = 100;     // Note that you can have different max lengths for each variable if you want.

            // Unpack the info from the buffer.
            CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, username, ref maxLength, domain, ref maxLength, password, ref maxLength);
            // Clear the memory allocated by CredUIPromptForWindowsCredentials.
            CoTaskMemFree(outCredBuffer);
            // Output info, escaping whitespace characters for the password.
            textBox1.Text += String.Format("Domain: {0}\n", domain);
            textBox1.Text += String.Format("Username: {0}\n", username);
            textBox1.Text += String.Format("Password (hashed): {0}\n", EscapeString(password.ToString()));
        }
示例#38
0
        public static void GetCredentialsVistaAndUp(string taskName, out NetworkCredential networkCredential)
        {
            CREDUI_INFO credui = new CREDUI_INFO
            {
                pszCaptionText = @"Please enter the credentials to use to schedule",
                pszMessageText = taskName
            };

            credui.cbSize = Marshal.SizeOf(credui);
            uint   authPackage = 0;
            IntPtr outCredBuffer;
            uint   outCredSize;
            bool   save   = false;
            int    result = CredUIPromptForWindowsCredentials(ref credui,
                                                              0,
                                                              ref authPackage,
                                                              IntPtr.Zero,
                                                              0,
                                                              out outCredBuffer,
                                                              out outCredSize,
                                                              ref save,
                                                              1 /* Generic */);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf   = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain   = 100;
            int maxPassword = 100;

            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
                                                   domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    CoTaskMemFree(outCredBuffer);
                    networkCredential = new NetworkCredential
                    {
                        UserName = usernameBuf.ToString(),
                        Password = passwordBuf.ToString(),
                        Domain   = domainBuf.ToString()
                    };
                    return;
                }
            }

            networkCredential = null;
        }
示例#39
0
 public static extern UInt32 CredUIPromptForCredentialsA(
     ref CREDUI_INFO creditUR,
     [In, MarshalAs(UnmanagedType.LPStr)]
     string targetName,
     IntPtr reserved1,
     UInt32 iError,
     [In, Out, MarshalAs(UnmanagedType.LPStr)]
     StringBuilder userName,
     UInt32 maxUserName,
     [In, Out, MarshalAs(UnmanagedType.LPStr)]
     StringBuilder password,
     UInt32 maxPassword,
     [MarshalAs(UnmanagedType.Bool)]
     ref bool pfSave,
     CREDUI_FLAGS flags);
示例#40
0
        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;
        }
示例#41
0
        public Task<Credentials> GetUserCredentialsAsync(string authority, bool invalidateStoredCredentials, CancellationToken cancellationToken = default(CancellationToken)) {
            _coreShell.AssertIsOnMainThread();

            var showDialog = invalidateStoredCredentials;
            var credentials = new Credentials();

            var passwordStorage = IntPtr.Zero;

            try {
                var userNameBuilder = new StringBuilder(CREDUI_MAX_USERNAME_LENGTH + 1);
                var save = false;
                var flags = CREDUI_FLAGS_EXCLUDE_CERTIFICATES | CREDUI_FLAGS_PERSIST | CREDUI_FLAGS_EXPECT_CONFIRMATION | CREDUI_FLAGS_GENERIC_CREDENTIALS;

                if(showDialog) {
                    flags |= CREDUI_FLAGS_ALWAYS_SHOW_UI;
                }

                var credui = new CREDUI_INFO {
                    cbSize = Marshal.SizeOf(typeof(CREDUI_INFO)),
                    hwndParent = _coreShell.AppConstants.ApplicationWindowHandle
                };

                // For password, use native memory so it can be securely freed.
                passwordStorage = SecurityUtilities.CreatePasswordBuffer();
                var err = CredUIPromptForCredentials(ref credui, authority, IntPtr.Zero, 0, userNameBuilder, userNameBuilder.Capacity, passwordStorage, CREDUI_MAX_PASSWORD_LENGTH, ref save, flags);
                if (err != 0) {
                    throw new OperationCanceledException();
                }

                credentials.UserName = userNameBuilder.ToString();
                credentials.Password = SecurityUtilities.SecureStringFromNativeBuffer(passwordStorage);
                credentials.Password.MakeReadOnly();
            } finally {
                if (passwordStorage != IntPtr.Zero) {
                    Marshal.ZeroFreeGlobalAllocUnicode(passwordStorage);
                }
            }

            return Task.FromResult(credentials);
        }
示例#42
0
        /// <summary>
        /// Shows a credential dialog.
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="message"></param>
        /// <param name="netCred"></param>
        /// <param name="image"></param>
        public static void Show(string caption, string message, ref NetworkCredential netCred, Bitmap image)
        {
            CREDUI_INFO credInf = new CREDUI_INFO();
            credInf.pszCaptionText = caption;
            credInf.pszMessageText = message;

            if (image != null)
            {
                credInf.hbmBanner = image.GetHbitmap();
            }
            credInf.cbSize = Marshal.SizeOf(credInf);
            uint authPackage = 0;
            IntPtr outCredBuffer = new IntPtr();
            uint outCredSize = 0;
            bool save = false;

            int result = CredUIPromptForWindowsCredentials(ref credInf, 0, ref authPackage, IntPtr.Zero, 0, ref outCredBuffer,
                ref outCredSize, ref save, Convert.ToInt32(CredUIWinFlags.CredUIWin_Generic));

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

            int maxUserName = 100;
            int maxDomain = 100;
            int maxPassword = 100;
            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName, domainBuf,
                    ref maxDomain, passwordBuf, ref maxPassword))
                {
                    CoTaskMemFree(outCredBuffer);
                    netCred = new NetworkCredential(usernameBuf.ToString(), passwordBuf.ToString(), domainBuf.ToString());
                    return;
                }
            }

            netCred = null;
        }
示例#43
0
        /// <summary>
        /// When overridden in a derived class, specifies a common dialog box.
        /// </summary>
        /// <param name="parentWindowHandle">A value that represents the window handle of the owner window for the common dialog box.</param>
        /// <returns>
        /// true if the dialog box was successfully run; otherwise, false.
        /// </returns>
        protected override bool RunDialog(IntPtr parentWindowHandle)
        {
            CREDUI_INFO info = new CREDUI_INFO(parentWindowHandle, this.Caption, this.Message, this.Banner);
            try
            {

                StringBuilder userName = new StringBuilder(this.UserName, maxStringLength);
                StringBuilder password = new StringBuilder(maxStringLength);
                bool save = this.SaveChecked;

                if (string.IsNullOrEmpty(this.Target)) this.Target = this.DefaultTarget;
                CredUIReturnCodes ret = CredUIPromptForCredentials(ref info, this.Target, IntPtr.Zero,
                    this.AuthenticationError, userName, maxStringLength, password, maxStringLength, ref save, this.Options);
                switch (ret)
                {
                    case CredUIReturnCodes.NO_ERROR:
                        /*if (save)
                        {
                            CredUIReturnCodes cret = CredUIConfirmCredentials(this.Target, false);
                            if (cret != CredUIReturnCodes.NO_ERROR && cret != CredUIReturnCodes.ERROR_INVALID_PARAMETER)
                            {
                                this.Options |= CredentialsDialogOptions.IncorrectPassword;
                                return false;
                            }
                        }*/
                        break;
                    case CredUIReturnCodes.ERROR_CANCELLED:
                        return false;
                    default:
                        throw new InvalidOperationException(String.Format("Call to CredUIPromptForCredentials failed with error code: {0}", ret));
                }

                if (this.EncryptPassword)
                {
                    // Convert the password to a SecureString
                    SecureString newPassword = StringBuilderToSecureString(password);

                    // Clear the old password and set the new one (read-only)
                    if (this.SecurePassword != null)
                        this.SecurePassword.Dispose();
                    newPassword.MakeReadOnly();
                    this.SecurePassword = newPassword;
                }
                else
                    this.Password = password.ToString();

                // Update other properties
                this.UserName = userName.ToString();
                this.SaveChecked = save;
                return true;
            }
            finally
            {
                info.Dispose();
            }
        }
 public static extern CredUIReturnCodes CredUIPromptForCredentials(
     CREDUI_INFO pUiInfo,  // Optional (one can pass null here)
     [MarshalAs(UnmanagedType.LPWStr)]
     string targetName,
     IntPtr Reserved,      // Must be 0 (IntPtr.Zero)
     int iError,
     [MarshalAs(UnmanagedType.LPWStr)]
     StringBuilder pszUserName,
     [MarshalAs(UnmanagedType.U4)]
     uint ulUserNameMaxChars,
     [MarshalAs(UnmanagedType.LPWStr)]
     StringBuilder pszPassword,
     [MarshalAs(UnmanagedType.U4)]
     uint ulPasswordMaxChars,
     ref int pfSave,
     CREDUI_FLAGS dwFlags);
示例#45
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;
 }
 private static void GetCredentialsVistaAndUp(string serverName, out string user, out string password)
 {
     var creduiInfo = new CREDUI_INFO();
     uint num2;
     creduiInfo = new CREDUI_INFO {
         pszCaptionText = "Please enter the credentails for " + serverName,
         pszMessageText = "Enter Credentials",
         cbSize = Marshal.SizeOf(creduiInfo)
     };
     uint authPackage = 0;
     IntPtr refOutAuthBuffer;
     var fSave = false;
     var num3 = CredUIPromptForWindowsCredentials(ref creduiInfo, 0, ref authPackage, IntPtr.Zero, 0, out refOutAuthBuffer, out num2, ref fSave, 1);
     var pszUserName = new StringBuilder(100);
     var pszPassword = new StringBuilder(100);
     var pszDomainName = new StringBuilder(100);
     int pcchMaxUserName = 100;
     int pcchMaxDomainame = 100;
     int pcchMaxPassword = 100;
     user = null;
     password = null;
     if ((num3 == 0) && CredUnPackAuthenticationBuffer(0, refOutAuthBuffer, num2, pszUserName, ref pcchMaxUserName, pszDomainName, ref pcchMaxDomainame, pszPassword, ref pcchMaxPassword))
     {
         CoTaskMemFree(refOutAuthBuffer);
         user = pszUserName.ToString();
         password = pszPassword.ToString();
     }
 }
        private static NetworkCredential PromptForCredential([NotNull] IWin32Window parent, string caption, string message, int authenticationError, [NotNull] SafeNativeMemory inCredBuffer)
        {
            Contract.Requires(parent != null);
            Contract.Requires(inCredBuffer != null);

            var save = true;
            uint authPackage = 0;
            IntPtr outCredBufferPtr;
            int outCredSize;

            var credui = new CREDUI_INFO
            {
                cbSize = Marshal.SizeOf(typeof(CREDUI_INFO)),
                pszCaptionText = caption,
                pszMessageText = message,
                hwndParent = parent.Handle
            };

            if (0 != NativeMethods.CredUIPromptForWindowsCredentials(ref credui, authenticationError, ref authPackage, inCredBuffer.DangerousGetHandle(), inCredBuffer.Size, out outCredBufferPtr, out outCredSize, ref save, 0))
                return null;

            using (var outCredBuffer = new SafeNativeMemory(outCredBufferPtr, outCredSize))
            {
                return UnpackAuthenticationBuffer(outCredBuffer);
            }
        }
示例#48
0
 private static extern CredUIReturnCodes CredUIPromptForWindowsCredentials(
         ref CREDUI_INFO creditUR,
         uint dwAuthError,
         ref uint pulAuthPackage,
         IntPtr pvInAuthBuffer,
         uint ulInAuthBufferSize,
         [Out] out IntPtr ppvOutAuthBuffer,
         out uint pulOutAuthBufferSize,
         [MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
         CREDUI_FLAGS_NEW dwFlags
     );
示例#49
0
        /// <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;
            }
        }
示例#50
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;
        }
示例#51
0
 private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO pUiInfo, string pszTargetName, IntPtr Reserved, int dwAuthError, StringBuilder pszUserName, int ulUserNameMaxChars, StringBuilder pszPassword, int ulPasswordMaxChars, ref int pfSave, CREDUI_FLAGS dwFlags);
示例#52
0
        /// <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()
        {
            // 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 = true;
            //bool save = true;
            //CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.DO_NOT_PERSIST | CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX | CREDUI_FLAGS.PERSIST;
            CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX;

            // Prompt the user
            CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, this.serverName, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags);

            _user = userID.ToString();

            _securePassword = new SecureString();
            for (int i = 0; i < userPassword.Length; i++)
            {
                _securePassword.AppendChar(userPassword[i]);
            }

            return (returnCode == CredUIReturnCodes.NO_ERROR);
        }
示例#53
0
		public static void RunProcesssAsUser(String processPath) {
			// Setup the flags and variables
			StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder();
			var credUI = new CREDUI_INFO();
			credUI.pszCaptionText = "Please enter the credentails for " + new ShellItem(processPath).DisplayName;
			credUI.pszMessageText = "DisplayedMessage";
			credUI.cbSize = Marshal.SizeOf(credUI);
			uint authPackage = 0;
			var outCredBuffer = new IntPtr();
			uint outCredSize;
			bool save = false;
			int result = CredUIPromptForWindowsCredentials(
				ref credUI,
				0,
				ref authPackage,
				IntPtr.Zero,
				0,
				out outCredBuffer,
				out outCredSize,
				ref save,
				1 /* Generic */);

			var usernameBuf = new StringBuilder(100);
			var passwordBuf = new StringBuilder(100);
			var domainBuf = new StringBuilder(100);

			int maxUserName = 100;
			int maxDomain = 100;
			int maxPassword = 100;
			if (result == 0) {
				if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName, domainBuf, ref maxDomain, passwordBuf, ref maxPassword)) {
					//TO_DO: ms documentation says we should call this but i can't get it to work
					//SecureZeroMem(outCredBuffer, outCredSize);

					//clear the memory allocated by CredUIPromptForWindowsCredentials
					Ole32.CoTaskMemFree(outCredBuffer);

					var pass = new SecureString();
					foreach (char _char in passwordBuf.ToString().ToCharArray()) {
						pass.AppendChar(_char);
					}

					using (var p = new Process()) {
						p.StartInfo.UseShellExecute = true;
						p.StartInfo.WorkingDirectory = Path.GetDirectoryName(processPath);
						p.StartInfo.FileName = processPath;
						p.StartInfo.UserName = usernameBuf.ToString();
						p.StartInfo.Password = pass;
						p.StartInfo.Domain = domainBuf.ToString();
						p.StartInfo.UseShellExecute = false;
						p.Start();
					}
				}
			}
		}
        public static NetworkCredential GetCredential()
        {
            CREDUI_INFO credui = new CREDUI_INFO();
            credui.pszCaptionText = "Please enter the credentials.";
            credui.pszMessageText = "DisplayedMessage";
            credui.cbSize = Marshal.SizeOf(credui);
            uint authPackage = 0;
            IntPtr outCredBuffer = new IntPtr();
            uint outCredSize;
            bool save = false;
            int result = CredUIPromptForWindowsCredentials(ref credui,0,ref authPackage,IntPtr.Zero,0,out outCredBuffer,out outCredSize,ref save,0x1);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain = 100;
            int maxPassword = 100;
            NetworkCredential netcreds = null;
            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName, domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    CoTaskMemFree(outCredBuffer);
                    netcreds = new NetworkCredential(usernameBuf.ToString(), passwordBuf.ToString(), domainBuf.ToString());
                }
            }

            return netcreds;
        }
示例#55
0
        internal static void Test()
        {
            CREDUI_INFO credUI = new CREDUI_INFO();
            credUI.cbSize = Marshal.SizeOf(credUI);
            credUI.pszCaptionText = "Hello";
            credUI.pszMessageText = "There";
            CREDUI_FLAGS_NEW flags = CREDUI_FLAGS_NEW.CREDUIWIN_AUTHPACKAGE_ONLY;
            bool save = false;
            uint authPackage = 0;
            IntPtr p;
            uint psize = 0;

            if (CredUIPromptForWindowsCredentials(ref credUI, 0, ref authPackage, IntPtr.Zero, 0, out p, out psize, ref save, flags) == CredUIReturnCodes.NO_ERROR)
            {

            }
        }
 private static void GetCredentialsXp(string serverName, out string user, out string password)
 {
     var creduiInfo = new CREDUI_INFO();
     var builder = new StringBuilder();
     var userName = new StringBuilder();
     creduiInfo = new CREDUI_INFO {
         cbSize = Marshal.SizeOf(creduiInfo)
     };
     var pfSave = false;
     const CREDUI_FLAGS flags = CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.ALWAYS_SHOW_UI;
     CredUIPromptForCredentials(ref creduiInfo, serverName, IntPtr.Zero, 0, userName, 100, builder, 100, ref pfSave, flags);
     user = userName.ToString();
     password = builder.ToString();
 }
示例#57
0
 extern static internal CredUIReturnCodes CredUIPromptForCredentials(
     ref CREDUI_INFO pUiInfo,
     string targetName,
     IntPtr Reserved,
     int dwAuthError,
     StringBuilder pszUserName,
     uint ulUserNameMaxChars,
     StringBuilder pszPassword,
     uint ulPaswordMaxChars,
     [MarshalAs(UnmanagedType.Bool), In(), Out()] ref bool pfSave,
     CREDUI_FLAGS dwFlags);
示例#58
0
 public static extern CredUIReturnCodes CredUIPromptForWindowsCredentials(
     ref CREDUI_INFO pUiInfo,
     uint dwAuthError,
     ref uint pulAuthPackage,
     IntPtr pvInAuthBuffer,
     uint ulInAuthBufferSize,
     out IntPtr ppvOutAuthBuffer,
     out uint pulOutAuthBufferSize,
     [MarshalAs(UnmanagedType.Bool)]ref bool pfSave,
     CredUIWinFlags dwFlags);
示例#59
0
 public static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO uiInfo, int authError, ref uint authPackage,
                                                              IntPtr InAuthBuffer, uint InAuthBufferSize,
                                                              out IntPtr refOutAuthBuffer, out uint refOutAuthBufferSize,
                                                              ref bool fSave, PromptForWindowsCredentialsFlags flags);
 public static extern uint CredUIPromptForWindowsCredentials(ref CREDUI_INFO info, int authError, ref uint authPackage, IntPtr inAuthBuffer,
     int inAuthBufferSize, out IntPtr refOutAuthBuffer, out int refOutAuthBufferSize, [MarshalAs(UnmanagedType.Bool)] ref bool fSave, int flags);