Click here to Skip to main content
15,886,035 members
Articles / Security

Elevating During Runtime

Rate me:
Please Sign up or sign in to vote.
4.93/5 (65 votes)
15 Feb 2013CPOL3 min read 146.2K   5.6K   107  
How can an application elevate itself to gain "Admin" rights during runtime
This article explains how to elevate an application during runtime. If your application would not require Admin rights except for certain occasions, you might prefer building your application with no specific requirement to be run in Admin mode, but when it needs to make a Registry change, only then, it will elevate itself to Admin mode. This article explains how that is done.
// How to Elevate during runtime - POC by Michael Haephrati
// �2011 Michael Haephrati (haephrati@gmail.com )

#include "stdafx.h"

BOOL IsRunAsAdministrator()
{
    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;
}

void ElevateNow()
{
	BOOL bAlreadyRunningAsAdministrator = FALSE;
	try
	{
		bAlreadyRunningAsAdministrator = IsRunAsAdministrator();
	}
	catch(...)
	{
		std::cout << "Failed to determine if application was running with admin rights" << std::endl;
		DWORD dwErrorCode = GetLastError();
		TCHAR szMessage[256];
		_stprintf_s(szMessage, ARRAYSIZE(szMessage), _T("Error code returned was 0x%08lx"),dwErrorCode);
		std::cout << szMessage << std::endl;
	}
	if(!bAlreadyRunningAsAdministrator)
	{
		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 << "End user did not allow elevation" << std::endl;
				}
			}
			else
			{
				_exit(1);  // Quit itself
			}
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	
	std::cout << "How to Elevate during runtime - POC by Michael Haephrati" << std::endl;
	
	std::cout << "Press Y <ENTER> to elevate, or any other key <ENTER> to quit" << std::endl;
	TCHAR ch = getchar();
	if(ch == 'Y' || ch == 'y')
	{
		if(IsRunAsAdministrator())
		{
			std::cout << "The applicaiton is already running with admin privileges" << std::endl;
		}
		else
		{
			ElevateNow();
		}

		std::cout << "(please send your comments to Michael Haephrati haephrati@gmail.com) Press any key to continue";
		std::cin.get();
		std::cin.get();
	}
	else
	{		
		std::cout << "(please send your comments to Michael Haephrati haephrati@gmail.com) Press any key to continue ...";
		std::cin.get();
		std::cin.get();
	}

	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
CEO Secured Globe, Inc.
United States United States
Michael Haephrati is a music composer, an inventor and an expert specializes in software development and information security, who has built a unique perspective which combines technology and the end user experience. He is the author of a the book Learning C++ , which teaches C++ 20, and was published in August 2022.

He is the CEO of Secured Globe, Inc., and also active at Stack Overflow.

Read our Corporate blog or read my Personal blog.





Comments and Discussions