Question

How to check is my application starts with admin rights? I use this code now:

public static bool IsUserAdministrator()
        {
            //bool value to hold our return value
            bool isAdmin;
            try
            {
                //get the currently logged in user
                WindowsIdentity user = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(user);
                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (UnauthorizedAccessException ex)
            {
                isAdmin = false;
            }
            catch (Exception ex)
            {
                isAdmin = false;
            }
            return isAdmin;
        }

This code checks user rights, I need to check the rights that application has. For example, I'm not the administrator but when the application starts with admin rights this code returns false. Thanks!

Was it helpful?

Solution

That's the correct approach to performing the check, I use it myself in my PowerShell profile to distinguish elevated sessions.

I suspect you're not taking into account the affect of User Access Control (UAC). When a user logs in they get a security token object allocated. This contains both their own security id (SID), the SIDs of groups they belong to and a list of privileges they have (and whether those privileges are enabled).

With UAC enabled, when you do an interactive login if you have certain privileges or are a member of the local administrators you get two* tokens: one with everything and a second with administrative access SIDs and privileges removed. The former token is used with each launched process, unless launched elevated when the latter token is used.

Thus an administrator cannot exercise their full power without an extra step – this helps prevent malware from being started with full control of the system.

The best tool for seeing this in action is Process Explorer. The Security tab of the process properties dialogue shows the contents of the process's security token (and adding the "Integrity Level" column to the main display will show what processes are elevated) – run Process Explorer elevated to see the full information.

So your code will only return true for a process run by an administrator that is also elevated (run as administrator).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top