2009-04-16 15 views
19

Nasze stacje robocze nie są członkami domeny, na której działa nasz serwer SQL. (W rzeczywistości nie są w domenie - nie pytaj).Jak zbudować funkcję RUNAS/NETONLY w programie (C#/.NET/WinForms)?

Kiedy używamy SSMS lub cokolwiek do połączenia z serwerem SQL, używamy RUNAS/NETONLY z DOMAIN \ user. Następnie wpisujemy hasło i uruchamia program. (RUNAS/NETONLY nie pozwala na dołączenie hasła do pliku wsadowego).

Mam więc aplikację .NET WinForms, która wymaga połączenia SQL, a użytkownicy muszą ją uruchomić, uruchamiając plik wsadowy z poleceniem RUNAS/NETONLY, a następnie uruchamiając EXE.

Jeśli użytkownik przypadkowo uruchomi plik EXE bezpośrednio, nie może połączyć się z serwerem SQL.

Kliknięcie prawym przyciskiem myszy na aplikacji i użycie opcji "Uruchom jako ..." nie działa (prawdopodobnie dlatego, że stacja robocza tak naprawdę nie zna domeny).

Szukam sposobu, aby aplikacja wykonała wewnętrznie funkcję RUNAS/NETONLY, zanim zacznie cokolwiek znaczącego.

Proszę zobaczyć ten link do opisu jak RunAs/netonly działa: http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982

myślę Zamierzam użyć LOGON_NETCREDENTIALS_ONLY z CreateProcessWithLogonW

Odpowiedz

3

Zebrałem te użyteczne linki:

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

Okazuje się, idę do muszą używać LOGON_NETCREDENTIALS_ONLY z CreateProcessWithLogonW. Zobaczę, czy uda mi się wykryć program, jeśli został uruchomiony w ten sposób, a jeśli nie, zebrać poświadczenia domeny i uruchomić się. W ten sposób będzie tylko jeden samodzielnie zarządzający EXE.

+0

Wiem, że to jest naprawdę stare, ale pierwsze dwa łącza (developmentnow.com i blrchen.spaces.live.com) są wyłączone. – chrnola

0

Przypuszczam, że nie można po prostu dodać użytkownik aplikacji do serwera sql, a następnie użyć uwierzytelniania sql zamiast uwierzytelniania systemu Windows?

+0

Nie. I rzeczywiście chcę, aby użytkownicy, którzy mają dostęp do tego panelu sterowania, byli sami. To jest jak pulpit kontrolny, który pokazuje wiele procesów i pozwala użytkownikom uruchamiać je, wyświetlać wyniki itd. –

6

Właśnie zrobiłem coś podobnego do tego używając ImpersonationContext. Jest bardzo intuicyjny w obsłudze i działa doskonale dla mnie.

Aby uruchomić jako inny użytkownik, składnia jest:

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

Oto klasa:

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

Użyłem podobnego kodu w niestandardowym instalatorze - jednak prawo "Działaj jako część systemu operacyjnego" jest bardzo potężne, a ja Odebrano od administratorów systemu spory oddźwięk dla przeciętnego użytkownika. YMMV oczywiście –

+0

Cóż, ten kod jest dobry tylko do logowania się lokalnie - w celu uzyskania poświadczeń dostępu zdalnego (w zasadzie tylko dla połączenia SQL) musisz użyć odpowiednika flagi/NETONLY, staram się to teraz przyłożyć. –

+1

Ten link ilustruje różnicę: http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982 - Być może trzeba będzie utworzyć nowy proces. –

2

Kod ten jest częścią klasy RunAs którego używamy, aby uruchomić proces zewnętrznego z podwyższonymi gabinetami. Podanie wartości null dla nazwy użytkownika & spowoduje wyświetlenie hasła ze standardowymi ostrzeżeniami UAC. Przekazując wartość dla nazwy użytkownika i hasła, można faktycznie uruchomić aplikację podniesioną bez monitu 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

Metoda ProcessStartInfo (i dlatego metoda Process.Start) nie ma żadnych równoważnych ustawień dla RUNAS/NETONLY, gdzie sieć poświadczenia są używane tylko dla połączenia sieciowego, a nie dla uprawnień lokalnych wątków/procesów. –

+0

Bummer ... może będziesz musiał uciekać się do PInvoke i CreateProcess. –

10

Wiem, że to stara nitka, ale była bardzo przydatna. Mam dokładnie taką samą sytuację jak Cade Roux, tak jak chciałem/funkcjonalność w stylu netonly.

Odpowiedź Johna Rascha działa z niewielką modyfikacją !!!

Dodaj następujące stałe (około 102 linii o konsystencji):

private const int LOGON32_LOGON_NEW_CREDENTIALS = 9; 

Następnie zmień wezwanie do LogonUser używać LOGON32_LOGON_NEW_CREDENTIALS zamiast LOGON32_LOGON_INTERACTIVE.

To zmiana , którą musiałem wprowadzić, aby to działało idealnie !!! Dziękuję John i Cade !!!

Oto zmodyfikowany kod w całości na łatwość kopiowania/wklejania:

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

Wiem, że to kilka lat później, ale dziękuję !!!!!!!!! To mi pomogło. –

Powiązane problemy