コード例 #1
0
 public static void PerformActionInsideImpersonatedContext(IPrincipal userPrinciple, Action actionToBePerformed)
 {
     if (userPrinciple == null)
     {
         actionToBePerformed();
     }
     else
     {
         WindowsIdentity             identity             = userPrinciple.Identity as WindowsIdentity;
         WindowsImpersonationContext impersonationContext = null;
         if (identity != null)
         {
             if (identity.IsAnonymous)
             {
                 identity = ServerUser.Identity as WindowsIdentity;
             }
             if (identity != null)
             {
                 impersonationContext = identity.Impersonate();
             }
         }
         try
         {
             actionToBePerformed();
         }
         catch (Exception)
         {
             impersonationContext?.Undo();
             identity = ServerUser.Identity as WindowsIdentity;
             if (identity != null)
             {
                 impersonationContext = identity.Impersonate();
             }
             try
             {
                 actionToBePerformed();
             }
             catch (Exception)
             {
                 //Ignore
             }
         }
         finally
         {
             impersonationContext?.Undo();
         }
     }
 }
コード例 #2
0
 public static void UndoImpersonation()
 {
     // restore original identity
     _windowsImpersonationContext?.Undo();
     _windowsImpersonationContext?.Dispose();
     _windowsImpersonationContext = null;
 }
コード例 #3
0
        /// <summary>
        /// The timer callback.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        protected virtual void TimerCallback(object sender)
        {
            if (!Monitor.TryEnter(this))
            {
                return;
            }

            WindowsImpersonationContext impersonationContext = null;

            if (this._primaryThreadIdentity != null)
            {
                impersonationContext = this._primaryThreadIdentity.Impersonate();
            }

            try
            {
                this.RunOnce();
            }
            finally
            {
                Monitor.Exit(this);

                impersonationContext?.Undo();
            }
        }
コード例 #4
0
ファイル: DoPutAction.cs プロジェクト: malotho-zz/Warewolf
        public override int ExecuteOperation()
        {
            var destination = Destination;

            if (!_pathWrapper.IsPathRooted(Destination.Path) && _whereToPut != null)
            {
                destination = ActivityIOFactory.CreatePathFromString(_whereToPut + "\\" + Destination.Path, Destination.Username, Destination.Password, Destination.PrivateKeyFile);
            }
            _fileLock.EnterWriteLock();
            try
            {
                using (_currentStream)
                {
                    if (ImpersonatedUser != null)
                    {
                        return(ExecuteOperationWithAuth(_currentStream, destination));
                    }
                    return(WriteData(_currentStream, destination));
                }
            }
            finally
            {
                _fileLock.ExitWriteLock();
                ImpersonatedUser?.Undo();
            }
        }
コード例 #5
0
ファイル: Impersonate.cs プロジェクト: pcluddite/tbasic
        public static int RunAs(string user, string pass, string domain, Delegate method, params object[] parms)
        {
            WindowsIdentity identity = null;
            WindowsImpersonationContext wic = null;

            if (string.IsNullOrEmpty(domain))
                domain = ".";

            try {
                IntPtr token;
                if (LogonUser(user, domain, pass, 0x09, 0x00, out token)) {
                    identity = new WindowsIdentity(token);
                    wic = identity.Impersonate(); // begin the impersonation

                    method.DynamicInvoke(parms);

                    return 0;
                }
                else {
                    return Marshal.GetLastWin32Error();
                }
            }
            finally {
                wic?.Undo(); // stop impersonation
            }
        }
コード例 #6
0
 /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
 public void Dispose()
 {
     impersonationContext?.Undo();
     if (ownId)
     {
         identity?.Dispose();
     }
     identity = null;
 }
コード例 #7
0
        public void Dispose()
        {
#if NETSTANDARD || NETCOREAPP
            NativeMethods.RevertToSelf();
#else
            impersonationContext?.Undo();
#endif
            token?.Dispose();
            identity?.Dispose();
        }
コード例 #8
0
        /// <summary>
        /// Stops impersonation.
        /// </summary>
        public void UndoImpersonation()
        {
            // restore saved requestor identity
            if (_wic != null)
            {
                _wic.Undo();
            }

            _wic            = null;
            IsImpersonating = false;
        }
コード例 #9
0
 private void UndoImpersonate()
 {
     if (_WindowsImpersonationContext != null)
     {
         _WindowsImpersonationContext.Undo();
         if (!_TokenHandle.Equals(IntPtr.Zero))
         {
             CloseHandle(_TokenHandle);
         }
     }
 }
コード例 #10
0
 public void Dispose()
 {
     if (wic != null)
     {
         wic.Undo();
     }
     if (tokenHandle != IntPtr.Zero)
     {
         CloseHandle(tokenHandle);
     }
 }
コード例 #11
0
 /// <summary>
 /// Dispose the UserImpersonation connection
 /// </summary>
 public void Dispose()
 {
     if (_windowsImpersonationContext != null)
     {
         _windowsImpersonationContext.Undo();
     }
     if (_tokenHandle != IntPtr.Zero)
     {
         CloseHandle(_tokenHandle);
     }
 }
コード例 #12
0
    public void Dispose()
    {
        if (userHandle != IntPtr.Zero)
        {
            CloseHandle(userHandle);

            userHandle = IntPtr.Zero;

            impersonationContext.Undo();
        }
    }
コード例 #13
0
        public int EjecutarBat()
        {
            WindowsImpersonationContext wic = setUser();

            int ret = 2;

            System.Diagnostics.Process process = new System.Diagnostics.Process();

            if (wic != null)
            {
                try
                {
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    startInfo.FileName    = "cmd.exe";
                    startInfo.Arguments   = "/C md pepe";
                    process.StartInfo     = startInfo;
                    process.Start();
                    process.WaitForExit();
                    log.Info("ExitCode: " + process.ExitCode.ToString());
                    process.Close();
                    ret = 1;
                }
                catch (Exception ex)
                {
                    wic.Undo();
                    log.Error("Error en impersonate ejecutar bat ", ex);
                }
                finally
                {
                    wic.Undo();

                    if (userHandle != IntPtr.Zero)
                    {
                        CloseHandle(userHandle);
                    }
                }
            }

            return(ret);;
        }
コード例 #14
0
 private void Unmount()
 {
     if (context != null)
     {
         context.Undo();
         context.Dispose();
     }
     if (identity != null)
     {
         identity.Dispose();
     }
 }
コード例 #15
0
        public static void CloseImpersonation(WindowsImpersonationContext impersonatedUser, IntPtr token)
        {
            impersonatedUser.Undo();


            bool isSuccess = CloseHandle(token);

            if (!isSuccess)
            {
                RaiseLastError();
            }
        }
コード例 #16
0
        static void Main(string[] args)
        {
            // Печатаем текущего пользователя
            WindowsIdentity wi = WindowsIdentity.GetCurrent();

            Console.WriteLine("Name={0} --> {1}", wi.Name, wi.IsAuthenticated);

            string UserName = "******";
            string Password = "******";

            // Для сохранения текущей имперсонации
            WindowsImpersonationContext impersonationContext = null;

            try
            {
                // Имперсонируем другого пользователя
                WindowsIdentity newIdentity;
                IntPtr          token          = IntPtr.Zero;
                IntPtr          tokenDuplicate = IntPtr.Zero;
                if (LogonUser(UserName, Environment.MachineName, Password,
                              LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        newIdentity = new WindowsIdentity(tokenDuplicate);
                        // При имперсонации возвращается текущее значение
                        impersonationContext = newIdentity.Impersonate();
                    }
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Ошибка ммперсонации пользователя {0}: {1}", UserName, Ex);
            }

            // Новая имперсонация
            WindowsIdentity wi1 = WindowsIdentity.GetCurrent();

            Console.WriteLine("Name={0} --> {1}", wi1.Name, wi1.IsAuthenticated);

            // Возвращаем предыдущую имперсонацию
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }

            // Печатаем снова
            WindowsIdentity wi2 = WindowsIdentity.GetCurrent();

            Console.WriteLine("Name={0} --> {1}", wi2.Name, wi2.IsAuthenticated);

            Console.ReadLine();
        }
コード例 #17
0
        /// <summary>
        ///     Reverts the user context to the Windows user represented by this object.
        /// </summary>
        public void Undo( )
        {
            if (_context != null)
            {
                _context.Undo( );
            }

            if (_identity != null)
            {
                _identity.Dispose( );
            }
        }
コード例 #18
0
ファイル: RevertToSelf.cs プロジェクト: keutmann/wspbuilder
 public void ReturnToImpersonatingCurrentUser()
 {
     try
     {
         if (ctx != null)
         {
             ctx.Undo();
             ctx = null;
         }
     }
     catch { }
 }
コード例 #19
0
        /// <summary>
        /// Executes the specified method under the specified credentials.
        /// </summary>
        /// <param name="methodToRunAs"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        public static void RunAs(RunAsDelegate methodToRunAs, string userName, string password, string domain)
        {
            IntPtr token           = IntPtr.Zero;
            IntPtr hTokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf() != 0)
                {
                    if (LogonUser(
                            userName,
                            domain,
                            password,
                            LOGON32_LOGON_INTERACTIVE,
                            LOGON32_PROVIDER_DEFAULT,
                            out token))
                    {
                        if (DuplicateToken(token, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref hTokenDuplicate) != 0)
                        {
                            WindowsIdentity tempWindowsIdentity = new WindowsIdentity(hTokenDuplicate);
                            using (WindowsImpersonationContext impersonationContext = tempWindowsIdentity.Impersonate())
                            {
                                methodToRunAs();
                                impersonationContext.Undo();
                            }
                        }
                        else
                        {
                            throw new ImpersonationException(userName);
                        }
                    }
                    else
                    {
                        throw new ImpersonationException(userName);
                    }
                }
                else
                {
                    throw new ImpersonationException(userName);
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (hTokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(hTokenDuplicate);
                }
            }
        }
コード例 #20
0
ファイル: Impersonar.cs プロジェクト: DialTecSoftware/Hersan
 /// <summary>
 /// Stops impersonation
 /// </summary>
 public static void Undo()
 {
     if (impersonatedUser != null)
     {
         impersonatedUser.Undo();
     }
     // Free the tokens.
     if (tokenHandle != IntPtr.Zero)
     {
         CloseHandle(tokenHandle);
     }
 }
        /// <summary>
        /// Executes the job definition.
        /// </summary>
        /// <param name="targetInstanceId">For target types of <see cref="T:Microsoft.SharePoint.Administration.SPContentDatabase"></see> this is the database ID of the content database being processed by the running job. This value is Guid.Empty for all other target types.</param>
        public override void Execute(Guid targetInstanceId)
        {
            string user     = Properties[KEY_USER] as string;
            string password = Properties[KEY_PWD] as string;

            if (string.IsNullOrEmpty(user) || password == null)
            {
                throw new ArgumentNullException("Username and password is required.");
            }

            if (user.IndexOf('\\') < 0)
            {
                throw new ArgumentException("Username must be in the form \"DOMAIN\\USER\"");
            }

            IntPtr userHandle = new IntPtr(0);
            WindowsImpersonationContext impersonatedUser = null;

            try
            {
                bool returnValue = NativeMethods.LogonUser(
                    user.Split('\\')[1],
                    user.Split('\\')[0],
                    password,
                    NativeMethods.LOGON32_LOGON_INTERACTIVE,
                    NativeMethods.LOGON32_PROVIDER_DEFAULT,
                    ref userHandle
                    );

                if (!returnValue)
                {
                    throw new Exception("Invalid Username");
                }
                WindowsIdentity newId = new WindowsIdentity(userHandle);
                impersonatedUser = newId.Impersonate();

                List <string> urls = Properties[KEY_URLS] as List <string>;
                if (urls == null)
                {
                    urls = Common.WebApplications.SetBackConnectionHostNames.GetUrls();
                }
                Common.WebApplications.SetBackConnectionHostNames.SetBackConnectionRegKey(urls);
            }
            finally
            {
                if (impersonatedUser != null)
                {
                    impersonatedUser.Undo();
                }

                NativeMethods.CloseHandle(userHandle);
            }
        }
コード例 #22
0
        /// <summary>
        /// Moves an existing store item into this collection, overwriting any existing items.
        /// </summary>
        /// <param name="source">The store item to move.</param>
        /// <param name="destinationName">The
        /// <see cref="IWebDavStoreItem" /> that refers to the item that was moved,
        /// in its new location.</param>
        /// <returns>
        /// The moved <see cref="IWebDavStoreItem" /> instance.
        /// </returns>
        /// <exception cref="System.Exception">Path to the source item not defined.</exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnauthorizedException">If the user is unauthorized or has no access</exception>
        /// <remarks>
        /// Note that the method should fail without creating or overwriting content in the
        /// target collection if the move cannot go through.
        /// </remarks>
        public IWebDavStoreItem MoveItemHere(IWebDavStoreItem source, string destinationName)
        {
            // try to get the path of the source item
            WebDavDiskStoreItem sourceItem = (WebDavDiskStoreItem)source;
            string sourceItemPath          = sourceItem.ItemPath;

            if (sourceItemPath.Equals(string.Empty))
            {
                throw new Exception("Path to the source item not defined.");
            }

            // We get the path of
            string destinationItemPath = Path.Combine(ItemPath, destinationName);

            // the moving of the item
            if (source.IsCollection)
            {
                try
                {
                    // Impersonate the current user and move the directory
                    WindowsImpersonationContext wic = Identity.Impersonate();
                    Directory.Move(sourceItemPath, destinationItemPath);
                    wic.Undo();
                }
                catch
                {
                    throw new WebDavUnauthorizedException();
                }

                // We return the moved file as a WebDAVDiskStoreDocument
                var collection = new WebDavDiskStoreCollection(this, destinationItemPath);
                _items.Add(destinationName, new WeakReference(collection));
                return(collection);
            }

            try
            {
                // Impersonate the current user and move the file
                WindowsImpersonationContext wic = Identity.Impersonate();
                File.Move(sourceItemPath, destinationItemPath);
                wic.Undo();
            }
            catch
            {
                throw new WebDavUnauthorizedException();
            }

            // We return the moved file as a WebDAVDiskStoreDocument
            WebDavDiskStoreDocument document = new WebDavDiskStoreDocument(this, destinationItemPath);

            _items.Add(destinationName, new WeakReference(document));
            return(document);
        }
コード例 #23
0
    public static void _1()
    {
        WindowsIdentity             newIdentity = null;
        WindowsImpersonationContext newContext  = null;

        try
        {
            // zmiana tozsamosci uzytkownika
            newIdentity = SqlContext.WindowsIdentity;
            newContext  = newIdentity.Impersonate();
            if (newContext != null)
            {
                using (SqlConnection oConn = new SqlConnection(@"Data Source=MSSQLSERVER64;Initial Catalog=AdventureWorks2008;User Id=labuser;Password=Passw0rd;"))
                {
                    SqlCommand oCmd = new SqlCommand(@"SELECT * FROM [AdventureWorks2008].[dbo].[Konta]", oConn);
                    oConn.Open();
                    SqlDataReader oRead = oCmd.ExecuteReader(CommandBehavior.CloseConnection);
                    // przywracamy kontekst tozsamosci
                    newContext.Undo();
                    // wyniki metoda Send
                    SqlContext.Pipe.Send(oRead);
                }
            }
            else
            {
                throw new Exception("zmiana tozsamosci ");
            }
        }
        catch (SqlException ex)
        {
            SqlContext.Pipe.Send(ex.Message.ToString());
        }
        finally
        {
            if (newContext != null)
            {
                newContext.Undo();
            }
        }
    }
コード例 #24
0
        public static void CreateAuthedUNCPath(string path, bool isDir = false)
        {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            // handle UNC path
            SafeTokenHandle safeTokenHandle;

            byte[] data = new byte[3];

            data[0] = (byte)'a';
            data[1] = (byte)'b';
            data[2] = (byte)'c';

            try
            {
                bool loginOk = LogonUser(ParserStrings.PathOperations_Correct_Username, "DEV2", ParserStrings.PathOperations_Correct_Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

                if (loginOk)
                {
                    using (safeTokenHandle)
                    {
                        WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                        using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                        {
                            if (!isDir)
                            {
                                // Do the operation here
                                File.WriteAllBytes(path, data);
                            }
                            else
                            {
                                Directory.CreateDirectory(path);
                            }

                            // remove impersonation now
                            impersonatedUser.Undo();
                        }
                    }
                }
                else
                {
                    // login failed
                    throw new Exception("Failed to authenticate for resource [ " + path + " ] ");
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #25
0
        public static void RunAs(RunAsDelegate MethodToRunAs, string Username, string Password, string Domain)
        {
            IntPtr                      imp_token;
            WindowsIdentity             wid_admin = null;
            WindowsImpersonationContext wic       = null;

            try
            {
                if (LogonUser(Username, string.IsNullOrEmpty(Domain) ? "." : Domain, Password, 9, 0, out imp_token))
                {
                    //the impersonation suceeded
                    wid_admin = new WindowsIdentity(imp_token);
                    wic       = wid_admin.Impersonate();
                    //run the delegate method
                    MethodToRunAs();
                }
                else
                {
                    throw new Exception(string.Format("Could not impersonate user {0} in domain {1} with the specified password.", Username, Domain));
                }
            }
            catch (Exception se)
            {
                int ret = Marshal.GetLastWin32Error();
                if (wic != null)
                {
                    wic.Undo();
                }
                throw new Exception("Error code: " + ret.ToString(), se);
            }
            finally
            {
                //revert to self
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
コード例 #26
0
 /// <summary>
 /// Roleback the impersonation if applied previously.
 /// </summary>
 public static void UndoImpersonate()
 {
     impersonatedUser.Undo();
     if (hToken != IntPtr.Zero)
     {
         CloseHandle(hToken);
     }
     if (dupeTokenHandle != IntPtr.Zero)
     {
         CloseHandle(dupeTokenHandle);
     }
     return;
 }
コード例 #27
0
 /// <summary>
 /// If the extension of the file is unknown, this method tries to find the right extension by filename.
 /// </summary>
 /// <param name="Username"></param>
 /// <param name="password"></param>
 /// <param name="domain"></param>
 /// <param name="path"></param>
 /// <param name="filename"></param>
 /// <returns></returns>
 public string CreateDirectory(string Username, string password, string domain, string path)
 {
     path = ConvertHostnameToIP(path);
     using (WindowsImpersonationContext impersonatedUser = Login(Username, password, domain))
     {
         try
         {
             Directory.CreateDirectory(path);
         }
         finally { impersonatedUser.Undo(); }
     }
     return("");
 }
コード例 #28
0
 public void Leave()
 {
     if (!IsInContext)
     {
         return;
     }
     _context.Undo();
     if (_token != IntPtr.Zero)
     {
         CloseHandle(_token);
     }
     _context = null;
 }
コード例 #29
0
 static void ImpersonateByService()
 {
     //using (WindowsImpersonationContext wic = ImpersonateService.GetImpersonationContext("bpm_admin", "Abc123", "tutorabc"))
     using (WindowsImpersonationContext wic = ImpersonateService.GetImpersonationContext("longoriayou", "Fgl77vxs589", "tutorabc"))
     {
         Console.WriteLine("impersonating...: " + WindowsIdentity.GetCurrent().Name);
         foreach (string dir in Directory.GetDirectories(directoryPath))
         {
             Console.WriteLine(dir);
         }
         wic.Undo();
     }
 }
コード例 #30
0
 /// <summary>
 /// This method closes the current impersonation context in order revert the user
 /// to his real principal.
 /// </summary>
 public void UndoImpersonation()
 {
     if (_context != null)
     {
         _context.Undo();
         _context = null;
     }
     if (_selfContext != null)
     {
         _selfContext.Undo();
         _selfContext = null;
     }
 }