News:

Masm32 SDK description, downloads and other helpful links
Message to All Guests
NB: Posting URL's See here: Posted URL Change

Main Menu

API call to check if program is being run as Administrator

Started by Don57, October 08, 2012, 07:37:55 AM

Previous topic - Next topic

Don57

Working on a small app that has to be run as an Administrator. I need to check if the user is running it as an administrator, but as usual I just get lost in the Microsoft web site. Any help would be appreciated.

qWord

The following function returns a nonzero value, if the process runs with administrator rights:include \masm32\include\Advapi32.inc
includelib \masm32\lib\Advapi32.lib
...
TokenElevation EQU 20
...
IsElevated proc
LOCAL b:BOOL
LOCAL hToken:HANDLE
LOCAL Elevation:TOKEN_ELEVATION
LOCAL cbSize:DWORD

    mov b,0
    mov hToken,0
   
    mov edx,rv(GetCurrentProcess)
    .if rv(OpenProcessToken,edx,TOKEN_QUERY,&hToken )
        mov cbSize,SIZEOF TOKEN_ELEVATION
        .if rv(GetTokenInformation, hToken, TokenElevation, &Elevation, SIZEOF Elevation, &cbSize )
            m2m b,Elevation.TokenIsElevated
        .endif
    .endif
    .if hToken
        invoke CloseHandle,hToken
    .endif
   
    mov eax,b
    ret
   
IsElevated endp

EDIT: This code does not work for WinXp
MREAL macros - when you need floating point arithmetic while assembling!

farrier


You can set your program--thru the manifest--to force admin rights:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
    processorArchitecture="X86"
    name="YourAppName"
    type="win32"/>

<description>Description of your application</description>
<!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="requireAdministrator"
          uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>


hth,

farrier


hfheatherfox07

Quote from: qWord on October 08, 2012, 08:29:31 AM
The following function returns a nonzero value, if the process runs with administrator rights:include \masm32\include\Advapi32.inc
includelib \masm32\lib\Advapi32.lib
...
TokenElevation EQU 20
...
IsElevated proc
LOCAL b:BOOL
LOCAL hToken:HANDLE
LOCAL Elevation:TOKEN_ELEVATION
LOCAL cbSize:DWORD

    mov b,0
    mov hToken,0
   
    mov edx,rv(GetCurrentProcess)
    .if rv(OpenProcessToken,edx,TOKEN_QUERY,&hToken )
        mov cbSize,SIZEOF TOKEN_ELEVATION
        .if rv(GetTokenInformation, hToken, TokenElevation, &Elevation, SIZEOF Elevation, &cbSize )
            m2m b,Elevation.TokenIsElevated
        .endif
    .endif
    .if hToken
        invoke CloseHandle,hToken
    .endif
   
    mov eax,b
    ret
   
IsElevated endp


Hey qWord ....

How would be the best way to incorporate that into an app ?
I have an example of checking for multiple instances ....How would be the best way to add your proc ?
Your code and your skills will be assimilated. Your programming language is irrelevant.
We are the ASM Borg and you will become part of us. Compile and be assembled.

clamicun

JJ,
bom dia.
As always, a very precise answer from you.
Thanks a lot.
Mic

mineiro

Found this on my hard disk,  have IsAdmin function inside, it's just a snippet of other program that I was working 4 years ago. Assemble as console.
Only tested on 32 bits, xp and win7.
I'd rather be this ambulant metamorphosis than to have that old opinion about everything

Vortex

The IsUserAnAdmin API function :

https://msdn.microsoft.com/en-us/library/windows/desktop/bb776463%28v=vs.85%29.aspx

A quick example :

.386
.model flat,stdcall
option casemap:none

include     \masm32\include\windows.inc
include     \masm32\include\kernel32.inc
include     \masm32\include\shell32.inc

includelib  \masm32\lib\kernel32.lib
includelib  \masm32\lib\shell32.lib

.code

start:

    invoke  IsUserAnAdmin
   
    invoke  ExitProcess,eax

END start


test.bat :

@IsUserAnAdmin.exe

@IF %ERRORLEVEL% == 1 ( echo The user is an administrator. ) ELSE ( echo The user is not an administrator. )

jj2007

End of client support: Windows Vista

But it works on Win7-64 ;)

clamicun

Many thanks to everybody who helped me.

mineiro, voce e Mineiro ?
Minha esposa e de Almenara/MG

clamicun

Last question...

INVOKE IsUserAnAdmin
Returns TRUE or FALSE

What's wrong with that function ?
So the whole check on the user is only one line.

Vortex

Hi clamicun,

As Jochen stated, Vista is the last client operating system supporting this API but it works on Windows 7 :

https://msdn.microsoft.com/en-us/library/windows/desktop/bb776463%28v=vs.85%29.aspx


jj2007

Quote from: Vortex on August 19, 2016, 03:22:55 AMbut it works on Windows 7 :

Not surprisingly, it works also on Windows 10. Microsoft doesn't risk a shitstorm...

Vortex

This application gets the username with the API function GetUserName and compares it against the list of the members of the Administrators group :

include         IsUserAdmin.inc

.data

WSTR            LocalGroup,"Administrators"
ResumeHandle    dd 0
_size           dd 64

.data?

buffer          dd ?
EntriesRead     dd ?
TotalEntries    dd ?
UserName        db 128 dup(?)

.code

start:

    invoke  GetUserNameW,ADDR UserName,ADDR _size

    invoke  NetLocalGroupGetMembers,NULL,ADDR LocalGroup,\
            3,ADDR buffer,MAX_PREFERRED_LENGTH,\
            ADDR EntriesRead,ADDR TotalEntries,ADDR ResumeHandle

    call    IsUserAdministrator

    push    eax

    invoke  NetApiBufferFree,buffer

    call    ExitProcess

IsUserAdministrator PROC USES esi edi ebx

    mov     ebx,EntriesRead
    mov     esi,buffer

CompareUserName:

    mov     edi,LOCALGROUP_MEMBERS_INFO_3.lgrmi3_domainandname[esi]
    mov     edx,edi
    sub     edx,2

    ;  Remove the slash symbol from the user name : COMPUTERNAME\User

FindSlash:

    add     edx,2
    cmp     BYTE PTR [edx],'\'
    jne     FindSlash
    add     edx,2

    invoke  ucCmp,edx,ADDR UserName
    test    eax,eax
    jz      @f
    mov     eax,1
    ret
@@:
    add     esi,SIZEOF LOCALGROUP_MEMBERS_INFO_3
    dec     ebx

    jnz     CompareUserName
    ret

IsUserAdministrator ENDP

END start


test.bat :

@IsUserAdmin.exe

@IF %ERRORLEVEL% == 1 ( echo The user is an administrator. ) ELSE ( echo The user is not an administrator. )

Zen

DON57,
There are numerous ways to check if Administrative Privileges are required to run an application (manifests),...or, to check if the current user has been granted Administrative Privileges. Most programmers use the easiest method (for example: IsUserAnAdmin, MSDN, which was introduced in Windows XP). QWORD's post (above) uses the best method: OpenProcessToken function, MSDN, and, then, actually enumerate the current user's Privileges with GetTokenInformation, MSDN. I have used methods similar to Vortex's (above),...it is the normal approach, and, it is usually adequate for the circumstances,...but, it can be easily screwed up. 
The problem is that the number of Privileges has increased in the various Windows Operating System versions over the years,...and, some of them are quite powerful,...super-privileges (see below),...so, it's good to know exactly which Privileges are enabled.
...Also, with the introduction of the User Account Control (UAC) beginning with Windows Vista, there are an enormous number of default security settings possible that the average computer user doesn't understand (and Privileges are disabled by default). Here is an excellent article, describing the features of the User Account Control (UAC): Security: Inside Windows Vista User Account Control, Mark Russinovich, TechNet, June 2007

This is from: Windows Internals, Sixth Edition, by, Mark Russinovich, David A. Solomon, and, Alex Ionescu, 2012
QuoteSuper Privileges:
Several privileges are so powerful that a user to which they are assigned is effectively a "super user" who has full control over a computer. These privileges can be used in an infinite number of ways to gain unauthorized access to otherwise off-limit resources and to perform unauthorized operations.
However, we'll focus on using the privilege to execute code that grants the user privileges not assigned to the user, with the knowledge that this capability can be leveraged to perform any operation on the local machine that the user desires. This section lists the privileges and discusses the ways that they can be exploited. Other privileges, such as Lock Pages In Physical Memory, can be exploited for denial-of-service attacks on a system, but these are not discussed. Note that on systems with UAC enabled, these privileges will be granted
only to applications running at high integrity level or higher, even if the account possesses them
:

■■ Debug programs A user with this privilege can open any process on the system (except for a Protected Process) without regard to the security descriptor present on the process. The user could implement a program that opens the LSASS process, for example, copy executable code into its address space, and then inject a thread with the CreateRemoteThread Windows API to execute the injected code in a more-privileged security context. The code could grant the user additional privileges and group memberships.
■■ Take Ownership This privilege allows a holder to take ownership of any securable object (even protected processes and threads) by writing his own SID into the owner field of the object's security descriptor. Recall that an owner is always granted permission to read and modify the DACL of the security descriptor, so a process with this privilege could modify the DACL to grant itself full access to the object and then close and reopen the object with full access. This would allow the owner to see sensitive data and to even replace system files that execute as part of normal system operation, such as LSASS, with his own programs that grant a user elevated privileges.
■■ Restore Files and Directories A user assigned this privilege can replace any file on the system with her own. She could exploit this power by replacing system files as described in the preceding paragraph.
■■ Load and Unload Device Drivers A malicious user could use this privilege to load a device driver into the system. Device drivers are considered trusted parts of the operating system that can execute within it with System account credentials, so a driver could launch privileged programs that assign the user other rights.
■■ Create a Token Object This privilege can be used in the obvious way to generate tokens that represent arbitrary user accounts with arbitrary group membership and privilege assignment.
■■ Act As Part of Operating System LsaRegisterLogonProcess, the function a process calls to establish a trusted connection to LSASS, checks for this privilege. A malicious user with this privilege can establish a trusted-LSASS connection and then execute LsaLogonUser, a function used to create new logon sessions. LsaLogonUser requires a valid user name and password and accepts an optional list of SIDs that it adds to the initial token created for a new logon session. The user could therefore use her own user name and password to create a new logon session that includes the SIDs of more privileged groups or users in the resulting token.

Note that the use of an elevated privilege does not extend past the machine boundary to the network, because any interaction with another computer requires authentication with a domain controller and validation of domain passwords. Domain passwords are not stored on a computer either in plain text or encrypted form, so they are not accessible to malicious code.