Click here to Skip to main content
Licence CPOL
First Posted 27 Jan 2012
Views 4,886
Bookmarked 26 times

Elevating during runtime

By | 27 Jan 2012 | Article
How can an applicaiton elevate itself to gain "Admin" rights during runtime

Download ElevateUAC.zip - 9.37 KB (Executable)

Download HowToElevate_By_Michael_Haephrati.zip - 10.1 KB (Source Code)

Introduction

This article explains how to elevate an applicaiton during runtime.

Background

Some actions and tasks require elevation to an Admin rights. The User Access Control mechanism (UAC) provides the protection required to prevent performing critical changes by users other than the ones with Admin privileges. For example, if your application needs to make a change in the Registry, it will require Admin users to run it.

What happens if your application would not require Admin rights except for certain occasions, i.e. during first run only. In such case, you might prefer building your application with no specific requirement to be ran in Admin mode, but when it needs to make a Registry change, only then, it will elevate itself to Admin mode.

Here is how that is done.

What is UAC

User Account Control (UAC) is a mechanism developed by Microsoft as part of the newer Windows versions (starting of Vista). It provides higher security level by limiting applications from performing sensitive and dangerous tasks without gaining administrative rights.

Is it really possible to elevate during runtime?

Well, not exactly. The entire idea behind UAC is to prevent users with limited access rights to perform tasks that require higher access rights, so when an applicaiton is executed in "user" mode, it can't change itself, as if it was initially ran in "Admin" mode. The trick is to be able to elevate itself during runtime, when required, by restarting it, elevated to "admin" this time.

Am I running in Admin mode?

This is the first question you should ask when you need to do something that requires administrative priveleges. If your applicaiton was already started in "admin" rights, there is no need to elevate. Only when a certain task you are about to perform, requries "admin" rights, and your applicaiton was started in "user" mode, you need to elevate. So to begin with, how can you determine if your application is ran elevated already.

First, you allocate and initilize a SID of the Admin group. According to MSDN, A security identifier (SID) is a unique value of variable length that is used to identify a security principal or security group in Windows operating systems. Well-known SIDs are a group of SIDs that identify generic users or generic groups. Their values remain constant across all operating systems.

Before we proceed, lets get familiar with another function, CheckTokenMembership:

The CheckTokenMembership function determines whether a specified security identifier (SID) is enabled in an access token. In order to determine group membership for tokens of applications, CheckTokenMembershipEx is used instead.

For our purpuse, we can call CheckTokenMembership and by doing so, enquire whether the SID is enabled in the primary access token of the process.

To sum the first part, here is how we check if our applicaiton is running with administrative priveleges:

//
BOOL IsAppRunningAsAdminMode()
{
    BOOL fIsRunAsAdmin = FALSE;
    DWORD dwError = ERROR_SUCCESS;
    PSID pAdministratorsGroup = NULL;

    // Allocate and initialize a SID of the administrators group.
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    if (!AllocateAndInitializeSid(
        &NtAuthority, 
        2, 
        SECURITY_BUILTIN_DOMAIN_RID, 
        DOMAIN_ALIAS_RID_ADMINS, 
        0, 0, 0, 0, 0, 0, 
        &pAdministratorsGroup))
    {
        dwError = GetLastError();
        goto Cleanup;
    }

    // Determine whether the SID of administrators group is enabled in 
    // the primary access token of the process.
    if (!CheckTokenMembership(NULL, pAdministratorsGroup, &fIsRunAsAdmin))
    {
        dwError = GetLastError();
        goto Cleanup;
    }

Cleanup:
    // Centralized cleanup for all allocated resources.
    if (pAdministratorsGroup)
    {
        FreeSid(pAdministratorsGroup);
        pAdministratorsGroup = NULL;
    }

    // Throw the error if something failed in the function.
    if (ERROR_SUCCESS != dwError)
    {
        throw dwError;
    }

    return fIsRunAsAdmin;
}
// 

If IsAppRunningAsAdminMode returns TRUE, then there is nothing left to be done, and everything is OK to continue with any task.

If it returns FALSE, then we need to elevate.

How to Elevate

Elevator.jpg

The way we elevate during runtime is obtaining the application name and path and executing it elevated to "Admin", while the currently running instance, of course, must terminate.

We also need to address the scenario in which the end user refuses to confirm this elevation, which is addressed, as you can see in the following code:

wchar_t szPath[MAX_PATH];
if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)))
{
    // Launch itself as admin
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"runas";
    sei.lpFile = szPath;
    sei.hwnd = NULL;
    sei.nShow = SW_NORMAL;
    if (!ShellExecuteEx(&sei))
    {
        DWORD dwError = GetLastError();
        if (dwError == ERROR_CANCELLED)
        {
            // The user refused to allow privileges elevation.
            std::cout << "User did not allow elevation" << std::endl;
        }
    }
    else
    {
        _exit(1);  // Quit itself
    }
}  

Running my POC

I have written a little POC to demonstrate this idea.

HowToElevate-1.jpg

After pressing "Y", the applicaiton will try to elevate itself, only if it is not ran in Admin privileges already.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Michael Haephrati

CEO
Michael Haephrati
Israel Israel

Member

Follow on Twitter Follow on Twitter
An inventor and an expert specilizes in software development and information security, who has built a unique perspective which combines technology and the end user experience.
 
Mr. Haephrati has founded Target Eye on 2000. The Target Eye Monitoring software was developed since then. Before inventing Target Eye, worked on many ventures starting from HarmonySoft, designing the first Graphical Multi-lingual word processor for Amiga computer. Other ventures included: Data Cleansing (as part of the DataTune system which was implemented in:the Standards Institute of Israel, The Israeli Export Institute, Bezeq Call, Microsoft Israel, Del Technologies and Elite), developed GIS systems, Credit Scoring computerized systems. Managed a great number of software and IS projects for: Telecom, New Zealand (1994-1995), Apple, Silicon Valley (1995-1996), Israeli Police, OCR for traffic tickets pilot and license plate number identification for road cameras (1995, as part of TIS, Project Manager). During 1998-2000 has developed a credit scoring system based on geographical statistical data, participating VISA CAL, Isracard, Bank Leumi and Bank Discount (Target Scoring, being the VP Business Development of a large Israeli institute).
 
Member of the London Institute of Directors (since 2001)
Member of the International Association of Financial Crimes Investigators (since 1998).
Member of IACTI – THE INTERNATIONAL ASSOCIATION OF COUNTERTERRORISM INVESTIGATORS. (since 2000).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 Pinmembermier5:54 1 Feb '12  
GeneralMy vote of 5 PinmemberJeff Kibling3:27 31 Jan '12  
GeneralMy vote of 3 PinmemberAssaf Levy21:40 30 Jan '12  
QuestionNo elevation - but process creation PinmemberAjay Vijayvargiya16:18 29 Jan '12  
AnswerRe: No elevation - but process creation PinmemberMichael Haephrati21:55 29 Jan '12  
GeneralRe: No elevation - but process creation Pinmemberzart_zurt3:36 30 Jan '12  
GeneralRe: No elevation - but process creation PinmemberMichael Haephrati5:04 30 Jan '12  
GeneralRe: No elevation - but process creation PinmemberAjay Vijayvargiya16:01 30 Jan '12  
GeneralRe: No elevation - but process creation PinmemberAjay Vijayvargiya15:58 30 Jan '12  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 27 Jan 2012
Article Copyright 2012 by Michael Haephrati
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid