简体   繁体   English

Impersonate()之后的ProtectedData.Unprotect()

[英]ProtectedData.Unprotect() after Impersonate()

The following code doesn't work: 以下代码不起作用:

IntPtr token = Win32Dll.LogonUser(“user1”, “mydomain”, “password1”);
WindowsIdentity id = new WindowsIdentity(token);
WindowsImpersonationContext ic = id.Impersonate();
byte[] unprotectedBytes = ProtectedData.Unprotect(passwordBytes, null, DataProtectionScope.CurrentUser);
password = Encoding.Unicode.GetString(unprotectedBytes);
ic.Undo();

The password is not decrypted. 密码未解密。

MSDN says MSDN说

"If you use this method during impersonation, you may receive the following error: "Key not valid for use in specified state." This error can be prevented by loading the profile of the user you want to impersonate, before calling the method." “如果在模拟过程中使用此方法,则可能会收到以下错误:“密钥在指定状态下无效。”可以通过在调用该方法之前加载要模拟的用户的配置文件来防止此错误。

Haven't tried this myself, but you could try to use the LoadUserProfile unmanaged API call. 我自己还没有尝试过,但是您可以尝试使用LoadUserProfile非托管API调用。 For more info, check here . 有关更多信息,请在此处检查。

There are some related SO questions . 有一些相关的SO问题

Here's what's going on: for DPAPI to work it needs the user's keying material which is derived in part from the user's logon credentials. 这是发生的事情:要使DPAPI正常工作,它需要用户的密钥材料,该材料部分来自用户的登录凭据。 This data is stored with the user's profile. 此数据与用户的个人资料一起存储。 That's why a process not running as the user must load the user's profile. 这就是为什么没有以用户身份运行的进程必须加载用户的配置文件的原因。

You must call UnloadUserProfile() using the data returned from LoadUserProfile() 您必须使用从LoadUserProfile()返回的数据调用UnloadUserProfile()

here's what you need to do: 这是您需要做的:

LogonUser() LogonUser()
Impersonate() 模仿()
LoadUserProfile() LoadUserProfile()
Encrypt() 加密()
UnloadUserProfile() UnloadUserProfile()
RevertImpersonation() (Undo() in .NET) RevertImpersonation()(.NET中的Undo())

You must check errors, using GetLastError(), every step of the way. 必须在每个步骤中都使用GetLastError()检查错误。

Note that for you to all this stuff basically requires the process be an admin account. 请注意,对于您来说,所有这些事情基本上都需要该过程为管理员帐户。 You need the backup and restore privileges to load a user's profile. 您需要备份和还原特权才能加载用户的配置文件。 If when calling LoadUserProfile you get a privilege not held error, then you need to: 如果在调用LoadUserProfile时遇到未保留特权的错误,那么您需要:

a) make sure the application account has backup and restore privs a)确保应用程序帐户具有备份和还原特权
b) the privs are enabled, by default they are not. b)启用了priv,默认情况下未启用。

You can enabled privs using AdjustTokenPrivileges() http://msdn.microsoft.com/en-us/library/aa375202(VS.85).aspx 您可以使用AdjustTokenPrivileges() http://msdn.microsoft.com/en-us/library/aa375202 (VS.85) .aspx启用privs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM