簡體   English   中英

線程可以作為其他用戶執行嗎? (.NET 2.0 / 3.5)

[英]Can a Thread be executed as another user? (.NET 2.0/3.5)

我有一個C#應用程序,可以對包含計算到動態程序集的源文件進行一些運行時編譯。 顯然,這帶來了嚴重的安全問題。

根據以下“公式”,將生成以下代碼,並創建一個動態程序集:

式:

Int32 _index = value.LastIndexOf('.');
String _retVal = value.Substring(_index + 1);
return _retVal;

生成的代碼:

using System;
namespace Dynamics
{
  public class Evaluator
  {
    public Object Evaluate(String value)
    {
      // Begin external code
      Int32 _index = value.LastIndexOf('.');
      String _retVal = value.Substring(_index + 1);
      return _retVal;
      // End external code
    }
  }
}

然后加載動態程序集,並通過反射執行Evaluate方法。 這很好。

問題在於惡意代碼注入的可能性很大,因此我想在“沙盒”線程中運行Evaluate方法(不進行任何非托管API調用)。 為了進行測試,我使用了內置的Windows匿名用戶,並提供了以下代碼:

Thread tSandbox = new Thread(
    new ParameterizedThreadStart(this.DoSandboxedEvaluation));
WindowsIdentity tIdentity = WindowsIdentity.GetAnonymous();
WindowsPrincipal tPrincipal = new WindowsPrincipal(i);

這給了我匿名用戶的身份和主體。 如何將此方法應用於線程tSandbox,以便該線程上的代碼在指定的安全上下文中運行,而無需使用非托管API調用?

謝謝!

AFAIK模仿其他用戶的唯一方法是通過不受管理的win32 api(例如LogonUser())...您可以通過互操作調用它們。

有這樣一個代碼示例在這里

如果您只需要匿名帳戶,則您可能已經很接近了-您只需將原理分配給線程(您可以通過設置System.Threading.CurrentPrinciple,在要更改的線程中運行的代碼來完成此工作)

但是,如果您需要驗證Windows用戶並將該身份分配給線程,我認為您將不得不對LogonUser()進行非托管調用。 我沒有辦法解決。

這是一些與匿名用戶一起使用的代碼(假定使用ASP.Net Web ApplicationProject,在該表單上有一個名為“ identityLabel”的標記,並且已分配onInit =“ IdentityLabelInit”)(請注意,代碼的運行方式取決於無論您是在IIS還是Cassini下運行它-在IIS下,初始身份都是匿名用戶。在Cassini下,初始身份是我。


        protected void IdentityLabelInit(object sender, EventArgs e)
        {
            System.Threading.Thread testThread = new Thread(ReportIdentity);
            testThread.Start();
            testThread.Join();
        }

        private void ReportIdentity()
        {
            identityLabel.InnerText = "Initialized: " + System.Threading.Thread.CurrentPrincipal.Identity.Name;
            System.Security.Principal.IPrincipal currentPrincipal = System.Threading.Thread.CurrentPrincipal;
            SetAnonymousIdentity();
            System.Security.Principal.IPrincipal newPrincipal = System.Threading.Thread.CurrentPrincipal;
            if (newPrincipal.Equals(currentPrincipal))
                identityLabel.InnerText += ("no change");
            else
                identityLabel.InnerText += " | new name: " + System.Threading.Thread.CurrentPrincipal.Identity.Name;
        }

        private void SetAnonymousIdentity()
        {
            WindowsIdentity tIdentity = WindowsIdentity.GetAnonymous();
            WindowsPrincipal tPrincipal = new WindowsPrincipal(tIdentity);
            System.Threading.Thread.CurrentPrincipal = tPrincipal;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM