gpt4 book ai didi

c - 如何在 Windows 7 中检索 Windows 服务的系统代理设置

转载 作者:行者123 更新时间:2023-11-30 15:00:13 24 4
gpt4 key购买 nike

我正在编写一个应用程序,该应用程序将作为服务运行,并将选择系统代理设置用于与外界通信。我尝试了 WinHttpGetIEProxyConfigForCurrentUser 但它无法检索当前用户的代理设置,这是显而易见的因为服务是在本地系统域下运行的。为了实现这一点,我必须让用户登录到我不希望应用程序用户这样做的服务。我读到了有关可以传递给 CreateService() 的 SERVICE_USER_OWN_PROCESS 参数,但我既没有在 WinNT.h 中找到它的声明,也不确定它是否会起作用。由于这个问题,应用程序的开发陷入了困境。有人可以帮忙吗?

最佳答案

我在当前用户的上下文中运行程序时遇到了类似的情况。

首先 - 在全局范围内的某个地方 - 定义以下变量:

 HANDLE hUsrToken;
HANDLE hDupToken;
int sessionId;

您需要获取当前用户的 session Id:

int getInteractiveSessinoId()
{
PWTS_SESSION_INFO pSessInfo;
ulong count; // Number of current user sessions
int result = -1;

if (!WTSEnumerateSessions(WTS_CURRENT_SERVER, 0, 1, &pSessInfo, &count))
{
printf("Getting session information failed with error %d\n", << GetLastError());
WTSFreeMemory(pSessInfo);
return -2;
}

for (ulong loop = 0; loop < count; loop++)
{
if (pSessInfo[loop].State == WTSActive)
{
printf("Session %d is currently active\n", pSessInfo[loop].SessionId);
result = pSessInfo[loop].SessionId;
break;
}
}

WTSFreeMemory(pSessInfo);
return result;
}

接下来您需要模拟当前用户(我将其称为“附加到 session ”):

bool attachToSession(int sessionId)
{
// We need to duplicate the token of the session's user
if (!WTSQueryUserToken(sessionId, &hUsrToken))
{
pritnf("Query the user token failed with error %d\n", GetLastError());
return false;
}

if (!DuplicateTokenEx(hUsrToken, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenImpersonation , &hDupToken))
{
printf("Duplicating a token failed with error %d\n", GetLastError());
return false;
}

if (!ImpersonateLoggedOnUser(hDupToken))
{
printf("Impersonating the user failed with error %d\n", GetLastError();
return false;
}

return true;
}

现在,在当前用户的上下文中做任何您想做的事情,完成后,从用户的上下文中恢复(或“分离”):

bool detachFromSession()
{
if (!RevertToSelf())
{
printf("Reverting the token failed with error %d\n", GetLastError());
return false;
}

(void)CloseHandle(hDupToken);
(void)CloseHandle(hUsrToken);

return true;
}

我不确定将 token 应用于当前(服务)线程是否是个好主意。我认为创建一个新线程是一个更好的主意,该线程执行您想要在用户上下文中执行的任何操作并将模拟 token 应用于它。所以你的代码部分可能如下所示:

HANDLE hUsrToken;
HANDLE hDupToken;
HANDLE hThread;
int sessionId;
DWORD threadId;

DWORD WINAPI MyThreadFunction(LPVOID lpParam)
{
// WinHttpGetIEProxyConfigForCurrentUser(...
}

sessionId = getInterActiveSessionId();

if (attachToSession(int sessionId) == false)
{
// Error handling
return;
}

hThread = CreateThread(NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
NULL, // argument to thread function
CREATE_SUSPENDED, // Delay execution
&threadId);

if (SetThreadToken(hThread, hDupToken) == false)
{
// Error handling
return;
}

ResumeThread(hThread);

我不能保证这会解决您的问题,但我希望它能解决。祝你好运!

关于c - 如何在 Windows 7 中检索 Windows 服务的系统代理设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42244124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com