Esempio n. 1
0
        public static WindowsIdentity GetProcessWindowsIdentity(Process process)
        {
            IntPtr tokenHandle = IntPtr.Zero;
            WindowsIdentity wi = null;
            try
            {
                tokenHandle = GetProcessTokenHandle(process);
                wi = new WindowsIdentity(tokenHandle);
            }
            catch
            {
                if (wi != null)
                {
                    wi.Dispose();
                }

                return null;
            }
            finally
            {
                if (tokenHandle != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(tokenHandle);
                }
            }

            return wi;
        }
 public NetworkImpersonationContext(string domain, string userName, string password)
 {
     if (!LogonUser(userName, domain, password, 9, 0, out _token))
         throw new Win32Exception();
     _identity = new WindowsIdentity(_token);
     try
     {
         _impersonationContext = _identity.Impersonate();
     }
     catch
     {
         _identity.Dispose();
         throw;
     }
 }
Esempio n. 3
0
        private IList<IActivityIOPath> ListDirectoriesAccordingToType(IActivityIOPath src, ReadTypes type)
        {
            IList<IActivityIOPath> result = new List<IActivityIOPath>();

            string path = src.Path;

            if (!path.EndsWith("\\") && PathIs(src) == enPathType.Directory)
            {
                path += "\\";
            }

            if (!RequiresAuth(src))
            {
                try
                {

                    IEnumerable<string> dirs;

                    if (!Dev2ActivityIOPathUtils.IsStarWildCard(path))
                    {
                        if (Directory.Exists(path))
                        {
                            dirs = GetDirectoriesForType(path, string.Empty, type);
                        }
                        else
                        {
                            throw new Exception("The Directory does not exist.");
                        }
                    }
                    else
                    {
                        // we have a wild-char path ;)
                        string baseDir = Dev2ActivityIOPathUtils.ExtractFullDirectoryPath(path);
                        string pattern = Dev2ActivityIOPathUtils.ExtractFileName(path);

                        dirs = GetDirectoriesForType(baseDir, pattern, type);
                    }

                    if (dirs != null)
                    {
                        foreach (string d in dirs)
                        {
                            result.Add(ActivityIOFactory.CreatePathFromString(d, src.Username, src.Password, true,src.PrivateKeyFile));
                        }
                    }
                }
                catch (Exception)
                {
                    throw new Exception("Directory not found [ " + src.Path + " ] ");
                }
            }
            else
            {

                try
                {
                    // handle UNC path
                    SafeTokenHandle safeTokenHandle;
                    bool loginOk = LogonUser(ExtractUserName(src), ExtractDomain(src), src.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

                    if (loginOk)
                    {
                        using (safeTokenHandle)
                        {

                            WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                            using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                            {
                                // Do the operation here

                                try
                                {

                                    IEnumerable<string> dirs;

                                    if (!Dev2ActivityIOPathUtils.IsStarWildCard(path))
                                    {
                                        dirs = GetDirectoriesForType(path, string.Empty, type);
                                    }
                                    else
                                    {
                                        // we have a wild-char path ;)
                                        string baseDir = Dev2ActivityIOPathUtils.ExtractFullDirectoryPath(path);
                                        string pattern = Dev2ActivityIOPathUtils.ExtractFileName(path);

                                        dirs = GetDirectoriesForType(baseDir, pattern, type);
                                    }

                                    if (dirs != null)
                                    {
                                        foreach (string d in dirs)
                                        {
                                            result.Add(ActivityIOFactory.CreatePathFromString(d, src.Username, src.Password, src.PrivateKeyFile));
                                        }
                                    }

                                }
                                catch (Exception)
                                {
                                    throw new Exception("Directory not found [ " + src.Path + " ] ");
                                }

                                // remove impersonation now
                                impersonatedUser.Undo();
                                newID.Dispose();
                            }
                        }
                    }
                    else
                    {
                        // login failed
                        throw new Exception("Failed to authenticate with user [ " + src.Username + " ] for resource [ " + src.Path + " ] ");
                    }
                }
                catch (Exception ex)
                {
                    Dev2Logger.Log.Error(ex);
                    throw;
                }

            }

            return result;
        }
Esempio n. 4
0
        public bool CreateDirectory(IActivityIOPath dst, Dev2CRUDOperationTO args)
        {
            bool result = false;

            if (args.Overwrite)
            {
                if (!RequiresAuth(dst))
                {
                    if (DirectoryExist(dst))
                    {
                        Delete(dst);
                    }
                    Directory.CreateDirectory(dst.Path);
                    result = true;
                }
                else
                {
                    try
                    {
                        // handle UNC path
                        SafeTokenHandle safeTokenHandle;
                        bool loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);


                        if (loginOk)
                        {
                            using (safeTokenHandle)
                            {

                                WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                                using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                                {
                                    // Do the operation here

                                    if (DirectoryExist(dst))
                                    {
                                        Delete(dst);
                                    }
                                    Directory.CreateDirectory(dst.Path);
                                    result = true;

                                    // remove impersonation now
                                    impersonatedUser.Undo();
                                }
                            }
                        }
                        else
                        {
                            // login failed, oh no!
                            throw new Exception("Failed to authenticate with user [ " + dst.Username + " ] for resource [ " + dst.Path + " ] ");
                        }
                    }
                    catch (Exception ex)
                    {
                        Dev2Logger.Log.Error(ex);
                        throw;
                    }
                }
            }
            else if (!args.Overwrite && !DirectoryExist(dst))
            {
                if (!RequiresAuth(dst))
                {
                    Directory.CreateDirectory(dst.Path);
                    result = true;
                }
                else
                {

                    try
                    {
                        // handle UNC path
                        SafeTokenHandle safeTokenHandle;
                        bool loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

                        if (loginOk)
                        {
                            using (safeTokenHandle)
                            {

                                WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                                using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                                {
                                    // Do the operation here

                                    Directory.CreateDirectory(dst.Path);
                                    result = true;

                                    // remove impersonation now
                                    impersonatedUser.Undo();
                                }
                                newID.Dispose();
                            }
                        }
                        else
                        {
                            // login failed
                            throw new Exception("Failed to authenticate with user [ " + dst.Username + " ] for resource [ " + dst.Path + " ] ");
                        }
                    }
                    catch (Exception ex)
                    {
                        Dev2Logger.Log.Error(ex);
                        throw;
                    }
                }
            }

            return result;
        }
Esempio n. 5
0
        public bool PathExist(IActivityIOPath dst)
        {
            bool result;

            if (!RequiresAuth(dst))
            {
                result = PathIs(dst) == enPathType.Directory ? Directory.Exists(dst.Path) : File.Exists(dst.Path);
            }
            else
            {

                try
                {
                    // handle UNC path
                    SafeTokenHandle safeTokenHandle;
                    bool loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);


                    if (loginOk)
                    {
                        using (safeTokenHandle)
                        {

                            WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                            using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                            {
                                // Do the operation here

                                result = PathIs(dst) == enPathType.Directory ? Directory.Exists(dst.Path) : File.Exists(dst.Path);

                                // remove impersonation now
                                impersonatedUser.Undo();
                            }
                            newID.Dispose();
                        }
                    }
                    else
                    {
                        // login failed
                        throw new Exception("Failed to authenticate with user [ " + dst.Username + " ] for resource [ " + dst.Path + " ] ");
                    }
                }
                catch (Exception ex)
                {
                    Dev2Logger.Log.Error(ex);
                    throw;
                }
            }

            return result;
        }
        internal Uid GetUidFromSamAccountName(String sAMAccountName)
        {
            WindowsIdentity windowsId = new WindowsIdentity(sAMAccountName);

            try
            {
                if (windowsId.User == null)
                {
                    throw new ConnectorException(_configuration.ConnectorMessages.Format(
                    "ex_SIDLookup", "An execption occurred during validation of user {0}.  The user's sid could not be determined.",
                    sAMAccountName));
                }
                return GetUidFromSid(windowsId.User);
            }
            finally
            {
                if (windowsId != null)
                {
                    windowsId.Dispose();
                    windowsId = null;
                }
            }
        }
Esempio n. 7
0
        internal Uid ValidateUserCredentials(string username, string password)
        {
            IntPtr tokenHandle = new IntPtr(0);
            try
            {
                const int LOGON32_PROVIDER_DEFAULT = 0;
                const int LOGON32_LOGON_INTERACTIVE = 2;
                const int LOGON32_LOGON_NETWORK = 3;

                tokenHandle = IntPtr.Zero;
                bool success = LogonUser(username, null, password, LOGON32_LOGON_NETWORK,
                                         LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
                if(!success)
                {
                    int lastWindowsError = Marshal.GetLastWin32Error();
                    if(lastWindowsError == ERROR_PASSWORD_MUST_CHANGE)
                    {
                        string message = _configuration.ConnectorMessages.Format("ex_PasswordMustChange",
                                                         "User password must be changed");

                        PasswordExpiredException pweException = new PasswordExpiredException(message);
                        pweException.Uid = GetUidFromSamAccountName(username);

                        throw pweException;
                    }
                    else if(lastWindowsError == ERROR_LOGON_FAILURE)
                    {
                        string message = _configuration.ConnectorMessages.Format(
                            "ex_InvalidCredentials", "Invalid credentials supplied for user {0}", username);

                        throw new InvalidCredentialException(message);
                    }
                    else if (lastWindowsError == ERROR_ACCOUNT_LOCKED_OUT)
                    {
                        string message = _configuration.ConnectorMessages.Format("ex_AccountLocked",
                                                                                 "User's account has been locked");
                        throw new InvalidCredentialException(message);
                    }
                    else if (lastWindowsError == ERROR_ACCOUNT_EXPIRED)
                    {
                        string message = _configuration.ConnectorMessages.Format("ex_AccountExpired",
                                                                                 "User account expired for user {0}", username);
                        throw new InvalidCredentialException(message);
                    }
                    else
                    {
                        // no idea what could have gone wrong, so log it and throw connector error
                        string errorMessage = string.Format(
                            "Windows returned error number {0} from LogonUser call", lastWindowsError);
                        LOGGER.TraceEvent(TraceEventType.Error, CAT_DEFAULT, errorMessage);
                        //TODO: Add localization
                        throw new ConnectorException(errorMessage);
                    }
                }
                WindowsIdentity windowsId = new WindowsIdentity(tokenHandle);
                Uid uid = GetUidFromSid(windowsId.User);
                windowsId.Dispose();
                return uid;
            }
            catch(Exception e)
            {
                LOGGER.TraceEvent(TraceEventType.Error, CAT_DEFAULT, e.Message);
                throw;
            }
            finally
            {
                if(tokenHandle != IntPtr.Zero)
                {
                    CloseHandle(tokenHandle);
                }
            }
        }