windows下c++提高程序权限

    xiaoxiao2025-10-23  1

    // If the caller has enabled the SeDebugPrivilege privilege, // the requested access is granted regardless of the contents of the security descriptor. // 如果开启了SeDebugPrivilege,则不用管安全说明符 //You can't grant yourself privileges that you don't already have. //Some other process (with higher privileges) has to grant them to you. // 不能授予你没有的权限,得靠其他的进程授予 ... int main(){ HANDLE hToken; BOOL bRet = OpenProcessToken( GetCurrentProcess(), // 进程句柄(当前进程) TOKEN_ALL_ACCESS, // 全权访问令牌 &hToken // 返回的参数 进程令牌句柄 (就是AdjustTokenPrivileges的第一个参数) ); // 获取进程的令牌句柄 if (bRet != TRUE) cout << "获取令牌句柄失败!" << endl; BOOL set = SetPrivilege(hToken, SE_DEBUG_NAME, TRUE); if (!set || GetLastError() != ERROR_SUCCESS) cout << "提升权限失败 error:" << GetLastError() << endl; return 0; } /* * 作用: 设置进程权限 * 输入: hToken 得到代表句柄 lpszPrivilege 要打开或关闭的权限名 bEnablePrivilege 打开还是关闭权限 * 输出: 执行结果BOOL值 * 前提: 是进程(当前账户)具备该权限,只是访问令牌中没有启用该权限。 如果进程的访问令牌中本身就没有关联该权限,这AdjustTokenPrivileges函数调用 将会返回ERROR_NOT_ALL_ASSIGNED(值为1300L)的错误码。 * 解决方法: 如何让进程具有该权限?可以通过“控制面板”—“管理工具”—“本地安全策略” —“本地策略”—“用户权利指派”设置将该权限关联到指定的用户分组或用户上。 * 参考网址: https://msdn.microsoft.com/zh-cn/library/windows/desktop/aa446619(v=vs.85).aspx */ BOOL SetPrivilege(HANDLE hToken, LPCTSTR lpszPrivilege, BOOL bEnablePrivilege) { TOKEN_PRIVILEGES tp; // 该结构包含一个数组,数据组的每个项指明了权限的类型和要进行的操作 LUID luid; // 查找 if (!LookupPrivilegeValue( NULL, // 系统的名字,null,在本地系统上查找权限 lookup privilege on local system lpszPrivilege, // 要找的权限名 privilege to lookup &luid)) // 通过指针返回权限的LUID receives LUID of privilege { printf("LookupPrivilegeValue error: %u\n", GetLastError()); return FALSE; } tp.PrivilegeCount = 1; // 要修改的特权数目 tp.Privileges[0].Luid = luid; // 代表不同特权类型 if (bEnablePrivilege) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; else tp.Privileges[0].Attributes = 0; // 调整访问令牌的权限 Enable the privilege or disable all privileges. if (!AdjustTokenPrivileges( hToken,// OpenProcessToken第三个指针参数传出的访问令牌的句柄 FALSE, // 是否禁用所有所有的特权 &tp, // 指明要修改的权限 sizeof(TOKEN_PRIVILEGES), // PreviousState的长度 NULL, // 存放修改前的访问权限的信息,可空 NULL)) // 实际PreviousState结构返回的大小 { printf("AdjustTokenPrivileges error: %u\n", GetLastError()); return FALSE; } if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) { printf("令牌在NewState参数中没有这个或这些权限 \n"); return FALSE; } return TRUE; } 转自:https://segmentfault.com/n/1330000003915940
    转载请注明原文地址: https://ju.6miu.com/read-1303429.html
    最新回复(0)