Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if windows user has a password set?

Tags:

c#

wmi

Question

I didn't know it would be this difficult to figure out but here I am.

I'm developing a net support client which has to detect if the current logged in user has a password set. I tried it with WMI checking the PasswordRequired property in the Win32_UserAccount class, but it returns false even if my account is password protected. I'm out of ideas...

(Background: I need this info to tell the user he has to set one so I can connect to him via remote desktop, which isn't very happy if the account is "unprotected". If there is a way to get around this I'd also accept a different solution.)

Sincerely yours
Nefarius

Solution

Easier than I thought, I managed it with the WinAPI function LogonUser and provide you this simple wrapper code:

    private bool PasswordRequired
    {
        get
        {
            IntPtr phToken;

            // http://www.pinvoke.net/default.aspx/advapi32/LogonUser.html
            bool loggedIn = LogonUser(Environment.UserName,
                null,
                "",
                (int)LogonType.LOGON32_LOGON_INTERACTIVE,
                (int)LogonProvider.LOGON32_PROVIDER_DEFAULT,
                out phToken);

            int error = Marshal.GetLastWin32Error();

            if (phToken != IntPtr.Zero)
                // http://www.pinvoke.net/default.aspx/kernel32/CloseHandle.html
                CloseHandle(phToken);

            // 1327 = empty password
            if (loggedIn || error == 1327)
                return false;
            else
                return true;
        }
    }

That's exactly what I needed, thank you all for your fast and competent answers, I can always count on you! =)

like image 647
Nefarius Avatar asked Jul 02 '11 10:07

Nefarius


People also ask

How do you check if Windows account has a password?

Click on the Control Panel. Go to User Accounts. Click on Manage your network passwords on the left. You should find your credentials here!


1 Answers

Why not just to try to LogonUser with empty password?

like image 57
adontz Avatar answered Sep 27 '22 16:09

adontz