2009-04-16 20 views
19

Le nostre workstation non sono membri del dominio su cui è installato SQL Server. (Non sono in realtà su un dominio - non chiedere).Come creare la funzionalità RUNAS/NETONLY in un programma (C# /. NET/WinForms)?

Quando si utilizza SSMS o qualsiasi cosa per connettersi a SQL Server, utilizziamo RUNAS/NETONLY con DOMINIO \ utente. Quindi digitiamo la password e avvia il programma. (RUNAS/NETONLY non consente di includere la password nel file batch).

Quindi ho un'applicazione .NET WinForms che richiede una connessione SQL e gli utenti devono avviarla eseguendo un file batch che ha la riga di comando RUNAS/NETONLY e quindi avvia l'EXE.

Se l'utente avvia accidentalmente l'EXE direttamente, non può connettersi a SQL Server.

Fare clic con il pulsante destro del mouse sull'app e utilizzare l'opzione "Esegui come ..." non funziona (presumibilmente perché la workstation non conosce realmente il dominio).

Sto cercando un modo per l'applicazione per eseguire internamente la funzionalità RUNAS/NETONLY prima che inizi a qualcosa di significativo.

Si prega di consultare questo link per una descrizione di come funziona RUNAS/netonly: http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982

sto pensando che ho intenzione di dover usare LOGON_NETCREDENTIALS_ONLY con CreateProcessWithLogonW

risposta

3

Ho raccolto questi link utili:

http://www.developmentnow.com/g/36_2006_3_0_0_725350/Need-help-with-impersonation-please-.htm

http://blrchen.spaces.live.com/blog/cns!572204F8C4F8A77A!251.entry

http://geekswithblogs.net/khanna/archive/2005/02/09/22430.aspx

http://msmvps.com/blogs/martinzugec/archive/2008/06/03/use-runas-from-non-domain-computer.aspx

Si scopre che ho intenzione di utilizzare LOGON_NETCREDENTIALS_ONLY con CreateProcessWithLogonW. Vedrò se riesco a rilevare se il programma è stato avviato in quel modo e, in caso contrario, raccogliere le credenziali del dominio e lanciare se stesso. In questo modo ci sarà solo un file EXE autosufficiente.

+0

So che questo è davvero vecchio, ma i primi due collegamenti (developmentnow.com e blrchen.spaces.live.com) sono sordi. – chrnola

0

suppongo che non si può semplicemente aggiungere un utente per l'app per SQL Server e quindi utilizzare l'autenticazione SQL piuttosto che l'autenticazione di Windows?

+0

Nope. E in realtà voglio che gli utenti che accedono a questo pannello di controllo siano se stessi. È come una dashboard di controllo che mostra un numero di processi e consente agli utenti di attivarli, vedere i risultati, ecc. –

6

Ho appena fatto qualcosa di simile a questo utilizzando un ImpersonationContext. È molto intuitivo da usare e ha funzionato perfettamente per me.

Per eseguire come un altro utente, la sintassi è:

using (new Impersonator("myUsername", "myDomainname", "myPassword")) 
{ 
    // code that executes under the new context... 
} 

Qui è la classe:

namespace Tools 
{ 
    #region Using directives. 
    // ---------------------------------------------------------------------- 

    using System; 
    using System.Security.Principal; 
    using System.Runtime.InteropServices; 
    using System.ComponentModel; 

    // ---------------------------------------------------------------------- 
    #endregion 

    ///////////////////////////////////////////////////////////////////////// 

    /// <summary> 
    /// Impersonation of a user. Allows to execute code under another 
    /// user context. 
    /// Please note that the account that instantiates the Impersonator class 
    /// needs to have the 'Act as part of operating system' privilege set. 
    /// </summary> 
    /// <remarks> 
    /// This class is based on the information in the Microsoft knowledge base 
    /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158 
    /// 
    /// Encapsulate an instance into a using-directive like e.g.: 
    /// 
    ///  ... 
    ///  using (new Impersonator("myUsername", "myDomainname", "myPassword")) 
    ///  { 
    ///   ... 
    ///   [code that executes under the new context] 
    ///   ... 
    ///  } 
    ///  ... 
    /// 
    /// Please contact the author Uwe Keim (mailto:[email protected]) 
    /// for questions regarding this class. 
    /// </remarks> 
    public class Impersonator : 
     IDisposable 
    { 
     #region Public methods. 
     // ------------------------------------------------------------------ 

     /// <summary> 
     /// Constructor. Starts the impersonation with the given credentials. 
     /// Please note that the account that instantiates the Impersonator class 
     /// needs to have the 'Act as part of operating system' privilege set. 
     /// </summary> 
     /// <param name="userName">The name of the user to act as.</param> 
     /// <param name="domainName">The domain name of the user to act as.</param> 
     /// <param name="password">The password of the user to act as.</param> 
     public Impersonator(
      string userName, 
      string domainName, 
      string password) 
     { 
      ImpersonateValidUser(userName, domainName, password); 
     } 

     // ------------------------------------------------------------------ 
     #endregion 

     #region IDisposable member. 
     // ------------------------------------------------------------------ 

     public void Dispose() 
     { 
      UndoImpersonation(); 
     } 

     // ------------------------------------------------------------------ 
     #endregion 

     #region P/Invoke. 
     // ------------------------------------------------------------------ 

     [DllImport("advapi32.dll", SetLastError = true)] 
     private static extern int LogonUser(
      string lpszUserName, 
      string lpszDomain, 
      string lpszPassword, 
      int dwLogonType, 
      int dwLogonProvider, 
      ref IntPtr phToken); 

     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
     private static extern int DuplicateToken(
      IntPtr hToken, 
      int impersonationLevel, 
      ref IntPtr hNewToken); 

     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
     private static extern bool RevertToSelf(); 

     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
     private static extern bool CloseHandle(
      IntPtr handle); 

     private const int LOGON32_LOGON_INTERACTIVE = 2; 
     private const int LOGON32_PROVIDER_DEFAULT = 0; 

     // ------------------------------------------------------------------ 
     #endregion 

     #region Private member. 
     // ------------------------------------------------------------------ 

     /// <summary> 
     /// Does the actual impersonation. 
     /// </summary> 
     /// <param name="userName">The name of the user to act as.</param> 
     /// <param name="domainName">The domain name of the user to act as.</param> 
     /// <param name="password">The password of the user to act as.</param> 
     private void ImpersonateValidUser(
      string userName, 
      string domain, 
      string password) 
     { 
      WindowsIdentity tempWindowsIdentity = null; 
      IntPtr token = IntPtr.Zero; 
      IntPtr tokenDuplicate = IntPtr.Zero; 

      try 
      { 
       if (RevertToSelf()) 
       { 
        if (LogonUser(
         userName, 
         domain, 
         password, 
         LOGON32_LOGON_INTERACTIVE, 
         LOGON32_PROVIDER_DEFAULT, 
         ref token) != 0) 
        { 
         if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) 
         { 
          tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); 
          impersonationContext = tempWindowsIdentity.Impersonate(); 
         } 
         else 
         { 
          throw new Win32Exception(Marshal.GetLastWin32Error()); 
         } 
        } 
        else 
        { 
         throw new Win32Exception(Marshal.GetLastWin32Error()); 
        } 
       } 
       else 
       { 
        throw new Win32Exception(Marshal.GetLastWin32Error()); 
       } 
      } 
      finally 
      { 
       if (token != IntPtr.Zero) 
       { 
        CloseHandle(token); 
       } 
       if (tokenDuplicate != IntPtr.Zero) 
       { 
        CloseHandle(tokenDuplicate); 
       } 
      } 
     } 

     /// <summary> 
     /// Reverts the impersonation. 
     /// </summary> 
     private void UndoImpersonation() 
     { 
      if (impersonationContext != null) 
      { 
       impersonationContext.Undo(); 
      } 
     } 

     private WindowsImpersonationContext impersonationContext = null; 

     // ------------------------------------------------------------------ 
     #endregion 
    } 

    ///////////////////////////////////////////////////////////////////////// 
} 
+0

Ho usato un codice simile in un programma di installazione personalizzato - tuttavia il diritto "Agisci come parte del sistema operativo" è molto potente e io ottenuto un sacco di pushback dagli amministratori di sistema nel concedere questo agli utenti medi. YMMV naturalmente –

+0

Bene, questo codice è valido solo per l'accesso locale - per le credenziali di accesso remoto (fondamentalmente solo per la connessione SQL) devi usare l'equivalente del flag/NETONLY, sto cercando di inchiodarlo subito. –

+1

Questo tipo di collegamento illustra la differenza: http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982 - Potrebbe essere necessario creare un nuovo processo. –

2

Questo codice fa parte di una classe RunAs che usiamo per lanciare un processo esterno con privilegi elevati. Passando null per nome utente & la password verrà richiesta con gli avvisi UAC standard. Quando si passa un valore per nome utente e password, è possibile avviare l'applicazione elevata senza il prompt UAC.

public static Process Elevated(string process, string args, string username, string password, string workingDirectory) 
{ 
    if(process == null || process.Length == 0) throw new ArgumentNullException("process"); 

    process = Path.GetFullPath(process); 
    string domain = null; 
    if(username != null) 
     username = GetUsername(username, out domain); 
    ProcessStartInfo info = new ProcessStartInfo(); 
    info.UseShellExecute = false; 
    info.Arguments = args; 
    info.WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(process); 
    info.FileName = process; 
    info.Verb = "runas"; 
    info.UserName = username; 
    info.Domain = domain; 
    info.LoadUserProfile = true; 
    if(password != null) 
    { 
     SecureString ss = new SecureString(); 
     foreach(char c in password) 
      ss.AppendChar(c); 
     info.Password = ss; 
    } 

    return Process.Start(info); 
} 

private static string GetUsername(string username, out string domain) 
{ 
    SplitUserName(username, out username, out domain); 

    if(domain == null && username.IndexOf('@') < 0) 
     domain = Environment.GetEnvironmentVariable("USERDOMAIN"); 
    return username; 
} 
+0

ProcessStartInfo (e quindi il metodo Process.Start) non ha impostazioni equivalenti a RUNAS/NETONLY, dove la rete le credenziali vengono utilizzate solo per la connessione di rete, non per le autorizzazioni thread/processo locali. –

+0

Bummer ... potrebbe essere necessario ricorrere a PInvoke e CreateProcess. –

10

So che questo è un thread vecchio, ma è stato molto utile. Ho esattamente la stessa situazione di Cade Roux, come volevo/netonly funzionalità di stile.

La risposta di John Rasch funziona con una piccola modifica !!!

Aggiungere la seguente costante (circa 102 linea di coerenza):

private const int LOGON32_LOGON_NEW_CREDENTIALS = 9; 

quindi modificare la chiamata a LogonUser utilizzare LOGON32_LOGON_NEW_CREDENTIALS anziché LOGON32_LOGON_INTERACTIVE.

Questo è il solo cambiamento che dovevo fare per farlo funzionare perfettamente !!! Grazie John e Cade !!!

Ecco il codice modificato in piena per facilità di copia/incolla:

namespace Tools 
{ 
    #region Using directives. 
    // ---------------------------------------------------------------------- 

    using System; 
    using System.Security.Principal; 
    using System.Runtime.InteropServices; 
    using System.ComponentModel; 

    // ---------------------------------------------------------------------- 
    #endregion 

    ///////////////////////////////////////////////////////////////////////// 

    /// <summary> 
    /// Impersonation of a user. Allows to execute code under another 
    /// user context. 
    /// Please note that the account that instantiates the Impersonator class 
    /// needs to have the 'Act as part of operating system' privilege set. 
    /// </summary> 
    /// <remarks> 
    /// This class is based on the information in the Microsoft knowledge base 
    /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158 
    /// 
    /// Encapsulate an instance into a using-directive like e.g.: 
    /// 
    ///  ... 
    ///  using (new Impersonator("myUsername", "myDomainname", "myPassword")) 
    ///  { 
    ///   ... 
    ///   [code that executes under the new context] 
    ///   ... 
    ///  } 
    ///  ... 
    /// 
    /// Please contact the author Uwe Keim (mailto:[email protected]) 
    /// for questions regarding this class. 
    /// </remarks> 
    public class Impersonator : 
     IDisposable 
    { 
     #region Public methods. 
     // ------------------------------------------------------------------ 

     /// <summary> 
     /// Constructor. Starts the impersonation with the given credentials. 
     /// Please note that the account that instantiates the Impersonator class 
     /// needs to have the 'Act as part of operating system' privilege set. 
     /// </summary> 
     /// <param name="userName">The name of the user to act as.</param> 
     /// <param name="domainName">The domain name of the user to act as.</param> 
     /// <param name="password">The password of the user to act as.</param> 
     public Impersonator(
      string userName, 
      string domainName, 
      string password) 
     { 
      ImpersonateValidUser(userName, domainName, password); 
     } 

     // ------------------------------------------------------------------ 
     #endregion 

     #region IDisposable member. 
     // ------------------------------------------------------------------ 

     public void Dispose() 
     { 
      UndoImpersonation(); 
     } 

     // ------------------------------------------------------------------ 
     #endregion 

     #region P/Invoke. 
     // ------------------------------------------------------------------ 

     [DllImport("advapi32.dll", SetLastError = true)] 
     private static extern int LogonUser(
      string lpszUserName, 
      string lpszDomain, 
      string lpszPassword, 
      int dwLogonType, 
      int dwLogonProvider, 
      ref IntPtr phToken); 

     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
     private static extern int DuplicateToken(
      IntPtr hToken, 
      int impersonationLevel, 
      ref IntPtr hNewToken); 

     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
     private static extern bool RevertToSelf(); 

     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
     private static extern bool CloseHandle(
      IntPtr handle); 

     private const int LOGON32_LOGON_INTERACTIVE = 2; 
     private const int LOGON32_LOGON_NEW_CREDENTIALS = 9; 
     private const int LOGON32_PROVIDER_DEFAULT = 0; 

     // ------------------------------------------------------------------ 
     #endregion 

     #region Private member. 
     // ------------------------------------------------------------------ 

     /// <summary> 
     /// Does the actual impersonation. 
     /// </summary> 
     /// <param name="userName">The name of the user to act as.</param> 
     /// <param name="domainName">The domain name of the user to act as.</param> 
     /// <param name="password">The password of the user to act as.</param> 
     private void ImpersonateValidUser(
      string userName, 
      string domain, 
      string password) 
     { 
      WindowsIdentity tempWindowsIdentity = null; 
      IntPtr token = IntPtr.Zero; 
      IntPtr tokenDuplicate = IntPtr.Zero; 

      try 
      { 
       if (RevertToSelf()) 
       { 
        if (LogonUser(
         userName, 
         domain, 
         password, 
         LOGON32_LOGON_NEW_CREDENTIALS, 
         LOGON32_PROVIDER_DEFAULT, 
         ref token) != 0) 
        { 
         if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) 
         { 
          tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); 
          impersonationContext = tempWindowsIdentity.Impersonate(); 
         } 
         else 
         { 
          throw new Win32Exception(Marshal.GetLastWin32Error()); 
         } 
        } 
        else 
        { 
         throw new Win32Exception(Marshal.GetLastWin32Error()); 
        } 
       } 
       else 
       { 
        throw new Win32Exception(Marshal.GetLastWin32Error()); 
       } 
      } 
      finally 
      { 
       if (token != IntPtr.Zero) 
       { 
        CloseHandle(token); 
       } 
       if (tokenDuplicate != IntPtr.Zero) 
       { 
        CloseHandle(tokenDuplicate); 
       } 
      } 
     } 

     /// <summary> 
     /// Reverts the impersonation. 
     /// </summary> 
     private void UndoImpersonation() 
     { 
      if (impersonationContext != null) 
      { 
       impersonationContext.Undo(); 
      } 
     } 

     private WindowsImpersonationContext impersonationContext = null; 

     // ------------------------------------------------------------------ 
     #endregion 
    } 

    ///////////////////////////////////////////////////////////////////////// 
} 
+1

So che questo è qualche anno più tardi, ma grazie !!!!!!!!! Questo mi ha aiutato un sacco. –