主要思想是:在Windows服务(System)中,通过模拟用户登录,获得Session ID,然后对当前用户注册表项操作。
public IntPtr GetTokenAsCurrentUser()
{
IntPtr hTokenUser = IntPtr.Zero;
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (String.Compare(@”NT AUTHORITY\SYSTEM”, userName, true) == 0)
{
int consoleSessionId = WTSGetActiveConsoleSessionId();
if (WTSQueryUserToken(consoleSessionId, out hTokenUser))
{
return hTokenUser;
}
}
return hTokenUser;
}
public bool GetCurrentUserSID(ref string CurrentUserSID)
{
IntPtr hUserToken = GetTokenAsCurrentUser();
if (hUserToken != IntPtr.Zero)
{
if (!ImpersonateLoggedOnUser(hUserToken))
{
return false;
}
CloseHandle(hUserToken);
System.Security.Principal.WindowsIdentity windowsIdentity = System.Secu