偽装による .NET プロセス権限の昇格
.NET の偽装機能は、管理者権限などの高い特権でプロセスを起動するための堅牢な方法を提供します。これは、プロセスで権限エラーが発生した場合に特に役立ちます。 偽装により、プロセスは別のユーザー アカウントでアクションを実行できます。 これは、WindowsIdentity
クラスと WindowsImpersonationContext
クラスを使用して実現されます。
これを示すコード例は次のとおりです。
public class ImpersonationHelper : IDisposable { IntPtr m_tokenHandle = IntPtr.Zero; WindowsImpersonationContext m_impersonatedUser; public ImpersonationHelper(string domain, string user, string password) { bool success = LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref m_tokenHandle); if (!success) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode); } m_impersonatedUser = new WindowsIdentity(m_tokenHandle).Impersonate(); } protected virtual void Dispose(bool disposing) { if (disposing) { m_impersonatedUser?.Undo(); } if (m_tokenHandle != IntPtr.Zero) CloseHandle(m_tokenHandle); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } // Usage: using (new ImpersonationHelper("xxx.blabla.com", "xxxx", "xxxx")) { if (!string.IsNullOrEmpty(txtFilename.Text)) Process.Start(txtFilename.Text); }
ImpersonationHelper
クラスは偽装を処理します。 資格情報がコンストラクターに渡され、オブジェクトが破棄されるまで偽装がアクティブになります。 Process.Start
呼び出しは、偽装されたユーザーの昇格された権限で実行されます。
安全性は低いものの、より単純な代替方法では、Process
クラスを直接使用します。
System.Diagnostics.Process proc = new System.Diagnostics.Process(); System.Security.SecureString ssPwd = new System.Security.SecureString(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = "filename"; proc.StartInfo.Arguments = "args..."; proc.StartInfo.Domain = "domainname"; proc.StartInfo.UserName = "username"; string password = "user entered password"; // Insecure - avoid in production // ... (Password handling should be significantly improved for security) ... proc.Start();
このメソッドは、ProcessStartInfo
内に認証情報を直接設定します。 重要なのは、この例でのパスワードの処理は非常に安全ではないため、運用環境では決して使用しないでください。 認証情報マネージャーを使用するなど、パスワードを安全に処理する方法が不可欠です。
これらの偽装手法により、開発者はプロセス権限を効果的に管理し、セキュリティのベストプラクティスを遵守しながら、昇格された権限を必要とするタスクを実行できるようになります。運用環境の実装では、安全なパスワード管理を必ず優先してください。
以上が.NET で偽装を使用して、昇格された特権でプロセスを起動するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。