模拟管理员帐户以编辑注册表项不起作用(C#) [英] Impersonate admin account to edit registry key not working (C#)

查看:68
本文介绍了模拟管理员帐户以编辑注册表项不起作用(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来编辑本地计算机配置单元中的注册表项("SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ ProfileList \%SID%').在我实际上尝试打开注册表项(具有写权限)之前,一切似乎都还不错.消息不允许请求的注册表访问"时引发SecurityException.我已经检查并重新检查了注册表项和我要模拟的用户的权限,所有这些都已签出.登录到模拟用户的帐户时,该代码运行良好,但是以受限用户身份登录时,该代码将失败.除了赋予线程管理特权外,仿冒工作都可以正常进行.任何有关如何解决此问题的想法将不胜感激!

I am using the following code to edit a registry key in the local machine hive ('SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%SID%'). Everything seems to be fine until I actually try to open the registry key (with write permissions); a SecurityException is thrown with the message 'Requested registry access is not allowed.' I've checked and rechecked the permissions for the registry key and the user I'm impersonating and it all checks out. The code runs fine when logged into the impersonated user's account, but when logged in as a restricted user, it fails. It's as if the impersonation works all except for giving the thread administrative privileges. Any ideas about how to fix this would be greatly appreciated!

string KEY_STR = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\" + WindowsIdentity.GetCurrent().User.Value;
WindowsImpersonationContext adminContext = null;
IntPtr tokenHandle = new IntPtr(0);
try
{
    LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
    if (tokenHandle.Equals(new IntPtr(0))) LogonUser(userName, computerName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
    WindowsIdentity adminIdentity = new WindowsIdentity(tokenHandle);
    adminContext = adminIdentity.Impersonate();
    RegistryKey key = Registry.LocalMachine.OpenSubKey(KEY_STR, true);
    key.SetValue("State", 0x60001);
    Console.Out.WriteLine("User profile changed to Mandatory.");
}
catch (Exception ex)
{
    Console.Out.WriteLine("\nUnable to set profile to Mandatory:\n\t" + ex.Message);
}
finally
{
    adminContext.Undo();
    if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle);
}

推荐答案

我拥有的令牌不足以对注册表进行写访问.我将使用作为系统运行的Windows服务来代替它.

The token I had was insufficient to get write access to the registry. I'm going to use a windows service running as system to accomplish this instead.

这篇关于模拟管理员帐户以编辑注册表项不起作用(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆