/// <summary>
        /// An impersonation safe way to check directory existence for this DeploymentController.
        /// </summary>
        /// <param name="directory">The directory for which an existence check is being requested</param>
        /// <param name="user">The user to impersonate</param>
        /// <param name="password">The impersonated user password</param>
        /// <param name="isLocal">Whether the impersonated user is local to this server</param>
        /// <returns>True if the directory can be found</returns>
        public virtual bool DirectoryExists(string directory, string user, string password, bool isLocal)
        {
            Impersonation impersonated    = null;
            bool          directoryExists = false;

            try
            {
                if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(password))
                {
                    impersonated = new Impersonation();
                    impersonated.Impersonate(user, password, !isLocal);
                }

                directoryExists = Directory.Exists(directory);

                if (!directoryExists)
                {
                    directoryExists = File.Exists(directory);
                }
            }
            finally
            {
                if (impersonated != null)
                {
                    impersonated.UnImpersonate();
                    impersonated = null;
                }
            }

            return(directoryExists);
        }
        /// <summary>
        /// An impersonation safe way to create a directory for this DeploymentController.
        /// </summary>
        /// <param name="directory">The directory to be created</param>
        /// <param name="user">The user to impersonate</param>
        /// <param name="password">The impersonated user password</param>
        /// <param name="isLocal">Whether the impersonated user is local to this server</param>
        public virtual void CreateDirectory(string directory, string user, string password, bool isLocal)
        {
            if (!DirectoryExists(directory, user, password, isLocal))
            {
                Impersonation impersonated = null;
                try
                {
                    if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(password))
                    {
                        impersonated = new Impersonation();
                        impersonated.Impersonate(user, password, !isLocal);
                    }

                    Directory.CreateDirectory(directory);
                }
                finally
                {
                    if (impersonated != null)
                    {
                        impersonated.UnImpersonate();
                        impersonated = null;
                    }
                }
            }
        }
Ejemplo n.º 3
0
        internal void Save(DataManager data)
        {
            FileStream fileStream = FileUtils.OpenForWrite(data.ResolvePath(FileName));

            if (fileStream != null)
            {
                WindowsImpersonationContext wi = Impersonation.Impersonate();

                try
                {
                    XmlSerializer ser = new XmlSerializer(typeof(DayExtra), Data.NamespaceURI);
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        ser.Serialize(writer, this);
                    }
                }
                catch (Exception e)
                {
                    ErrorTrace.Trace(TraceLevel.Error, e);
                    // truncate the file if this fails
                    fileStream.SetLength(0);
                }
                finally
                {
                    fileStream.Close();
                }

                wi.Undo();
            }
        }
        /// <summary>
        /// An impersonation safe way to check file existence for this DeploymentController.
        /// </summary>
        /// <param name="file">The file for which an existence check is being requested</param>
        /// <param name="user">The user to impersonate</param>
        /// <param name="password">The impersonated user password</param>
        /// <param name="isLocal">Whether the impersonated user is local to this server</param>
        /// <returns>True if the file can be found</returns>
        public virtual bool FileExists(string file, string user, string password, bool isLocal)
        {
            Impersonation impersonated = null;
            bool          fileExists   = false;

            try
            {
                if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(_ImpersonationPassword))
                {
                    impersonated = new Impersonation();
                    impersonated.Impersonate(user, _ImpersonationPassword, !isLocal);
                }

                fileExists = File.Exists(file);

                if (!fileExists)
                {
                    fileExists = Directory.Exists(file);
                }
            }
            finally
            {
                if (impersonated != null)
                {
                    impersonated.UnImpersonate();
                    impersonated = null;
                }
            }

            return(fileExists);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Start impersonating the other account.
        /// </summary>
        /// <returns></returns>
        public IDisposable Impersonate()
        {
            var impersonation = new Impersonation(DomainName, UserName, Password.PrivateValue);

            impersonation.Impersonate();
            return(impersonation);
        }
 public void ThenImpersonateFails()
 {
     // Act / Assert
     Assert.Throws <InvalidOperationException>(
         () =>
         Impersonation.Impersonate(this._user, this._password));
 }
        /// <summary>
        /// An impersonation safe way to get a directory listing for this DeploymentController.
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="directoryFilter"></param>
        /// <param name="recurse"></param>
        /// <param name="user">The user to impersonate</param>
        /// <param name="password">The impersonated user password</param>
        /// <param name="isLocal">Whether the impersonated user is local to this server</param>
        /// <returns>The directory list</returns>
        public List <string> ListDirectories(string directory, string directoryFilter, bool recurse, string user, string password, bool isLocal)
        {
            try
            {
                if (DirectoryExists(directory, user, password, isLocal))
                {
                    Impersonation impersonated = null;
                    try
                    {
                        if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(password))
                        {
                            impersonated = new Impersonation();
                            impersonated.Impersonate(user, password, !isLocal);
                        }

                        return(STEM.Sys.IO.Directory.STEM_GetDirectories(directory, directoryFilter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly, true));
                    }
                    finally
                    {
                        if (impersonated != null)
                        {
                            impersonated.UnImpersonate();
                            impersonated = null;
                        }
                    }
                }
            }
            catch { }

            return(new List <string>());
        }
Ejemplo n.º 8
0
        public async Task <SqlConnection> OpenConnection(Instance instance)
        {
            if (instance == null)
            {
                logger.Error("ConnectionManager.OpenConnection: get null instance");
                return(null);
            }

            Impersonation       impersonation = null;
            ImpersonationResult impResult     = null;

            connection = new SqlConnection(BuildConnectionString(instance));


            if (instance.Authentication == AuthenticationType.Windows)
            {
                impersonation = new Impersonation();
                impResult     = impersonation.Impersonate(instance.Login, null, instance.Password);//тут

                if (impResult.HasError)
                {
                    logger.Error("Imperosnation error: ConnectionManager.OpenConnection: Instance id =" + instance.Id);
                }
                else
                {
                    logger.Debug("Impersonation oK instance id =" + instance.Id);
                }

                return(null);
            }


            try
            {
                //ConfigureAwait(true); to return to the same context to do undo imersonation for the same thread
                await connection.OpenAsync().ConfigureAwait(true);
            }
            catch (Exception e)
            {
                logger.Error("ConnectionManager.OpenConnection: Error open connection  instance=" + instance.InstanceName, e);
                return(null);
            }
            finally
            {
                if (impResult != null && impersonation != null)
                {
                    if (!impResult.HasError)
                    {
                        impersonation.UndoImpersonation(impResult.User);
                    }
                }
            }

            return(connection);
        }
Ejemplo n.º 9
0
        public void ImpersonationSuccessfulLogonTest()
        {
            // For this test to work, ensure there is a generic Credential Manager entry called ImpersonationUser with working credentials
            const string workingTarget = "ImpersonationUser";
            var          currentUser   = Impersonation.CurrentUser;

            Impersonation.Impersonate(workingTarget);
            Assert.AreNotEqual(currentUser, Impersonation.CurrentUser, "Users are different after impersonating");
            Impersonation.StopImpersonating();
            Assert.AreEqual(currentUser, Impersonation.CurrentUser, "Orginal user restored after stopping impersonation");
        }
Ejemplo n.º 10
0
 public void ImpersonationFailedLogonTest()
 {
     try
     {
         Impersonation.Impersonate(Target);
         Assert.Fail("No security exception thrown after impersonating with wrong credentials");
     }
     catch (SecurityException se)
     {
         Assert.AreEqual($"Could not impersonate user '{UserName}' for domain '{Domain}'", se.Message);
     }
 }
Ejemplo n.º 11
0
        public static void Save(SeoMetaTags seoConfig)
        {
            System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

            XmlSerializer ser = new XmlSerializer(typeof(SeoMetaTags));

            using (StreamWriter writer = new StreamWriter(MetaConfigFile))
            {
                ser.Serialize(writer, seoConfig);
            }

            wi.Undo();
        }
Ejemplo n.º 12
0
        public static void Save(SiteConfig siteConfig)
        {
            System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

            XmlSerializer ser = new XmlSerializer(typeof(SiteConfig));

            using (StreamWriter writer = new StreamWriter(SiteConfig.GetConfigFilePathFromCurrentContext()))
            {
                ser.Serialize(writer, siteConfig);
            }

            wi.Undo();
        }
Ejemplo n.º 13
0
        public void ImpersonationCredentialNotFoundTest()
        {
            const string unknownTarget = "@Unknown!Target$";

            try
            {
                Impersonation.Impersonate(unknownTarget);
                Assert.Fail("No security exception thrown after specifying unknown target");
            }
            catch (SecurityException se)
            {
                Assert.IsTrue(se.Message.StartsWith($"Could not find target '{unknownTarget}' in Generic section of Credential Manager for user '",
                                                    StringComparison.InvariantCultureIgnoreCase));
            }
        }
Ejemplo n.º 14
0
        void WriteEventDataItem(EventDataItem logItem, LogCategory category, ReaderWriterLock lockObject,
                                EventDataItemFormatter formatter)
        {
            if (logItem == null)
            {
                throw new ArgumentNullException("logItem");
            }

            if (lockObject == null)
            {
                throw new ArgumentNullException("lockObject");
            }

            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }

            try
            {
                using (Impersonation.Impersonate())
                {
                    // Archive last day's log files.
                    if (!File.Exists(String.Format("{0}.zip", GetLogPath(logItem.EventTimeUtc, LogCategory.Event))))
                    {
                        ArchiveLogFiles(logItem.EventTimeUtc.AddDays(-1));
                    }

                    lockObject.AcquireWriterLock(TimeSpan.FromMilliseconds(250));

                    using (StreamWriter writer = new StreamWriter(GetLogPath(logItem.EventTimeUtc, category), true))
                    {
                        writer.WriteLine(formatter(logItem));
                    }
                }
            }
            catch (Exception e)
            {
                ErrorTrace.Trace(TraceLevel.Error, e);
            }
            finally
            {
                if (lockObject.IsWriterLockHeld)
                {
                    lockObject.ReleaseWriterLock();
                }
            }
        }
Ejemplo n.º 15
0
        public static async Task <string> Check(string servername, string instanceName, string login, string pswd, bool windowsoauth)
        {
            String connString = BuildConnectionString(servername, instanceName, login, pswd, windowsoauth);

            Impersonation       impersonation = null;
            ImpersonationResult impResult     = null;

            SqlConnection connection = new SqlConnection(connString);

            if (windowsoauth)
            {
                impersonation = new Impersonation();
                impResult     = impersonation.Impersonate(login, null, pswd);

                if (impResult.HasError)
                {
                    return("Windows impersonation error!");
                }
            }


            try
            {
                await connection.OpenAsync().ConfigureAwait(true);

                connection.Close();
            }
            catch (Exception e)
            {
                return("Open connection error!\n" + e.Message);
            }
            finally
            {
                if (impResult != null && impersonation != null)
                {
                    if (!impResult.HasError)
                    {
                        impersonation.UndoImpersonation(impResult.User);
                    }
                }
            }


            return("Ok!");
        }
Ejemplo n.º 16
0
        void WriteLogDataItem(LogDataItem logItem, LogCategory category, ReaderWriterLock lockObject,
                              LogDataItemFormatter formatter)
        {
            if (logItem == null)
            {
                throw new ArgumentNullException("logItem");
            }

            if (lockObject == null)
            {
                throw new ArgumentNullException("lockObject");
            }

            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }

            try
            {
                using (Impersonation.Impersonate())
                {
                    lockObject.AcquireWriterLock(TimeSpan.FromMilliseconds(250));

                    using (StreamWriter writer = new StreamWriter(GetLogPath(logItem.RequestedUtc, category), true))
                    {
                        writer.WriteLine(formatter(logItem));
                    }
                }
            }
            catch (Exception e)
            {
                ErrorTrace.Trace(TraceLevel.Error, e);
            }
            finally
            {
                if (lockObject.IsWriterLockHeld)
                {
                    lockObject.ReleaseWriterLock();
                }
            }
        }
Ejemplo n.º 17
0
        internal void Save(DataManager data)
        {
            string fullPath = data.ResolvePath(FileName);

            // We use the internal list to circumvent ignoring
            // items where IsPublic is set to false.
            if (Entries.Count == 0)
            {
                if (File.Exists(fullPath))
                {
                    File.Delete(fullPath);
                }
            }
            else
            {
                System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

                FileStream fileStream = FileUtils.OpenForWrite(fullPath);

                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(DayEntry), Data.NamespaceURI);
                        using (StreamWriter writer = new StreamWriter(fileStream))
                        {
                            ser.Serialize(writer, this);
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }

                wi.Undo();
            }
        }
Ejemplo n.º 18
0
        internal void Impersonate(out Impersonation token)
        {
            try
            {
                if (!String.IsNullOrEmpty(ImpersonationUser) && !String.IsNullOrEmpty(ImpersonationPassword))
                {
                    Impersonation i = new Impersonation();
                    token = i;

                    i.Impersonate(ImpersonationUser, ImpersonationPassword, LocalUserImpersonation);
                }
                else
                {
                    token = null;
                }
            }
            catch (Exception ex)
            {
                STEM.Sys.EventLog.WriteEntry("SMB.Authentication.Impersonate", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                throw ex;
            }
        }
        /// <summary>
        /// An impersonation safe way to get FileInfo for this DeploymentController.
        /// </summary>
        /// <param name="file">The file for which FileInfo is being requested</param>
        /// <param name="user">The user to impersonate</param>
        /// <param name="password">The impersonated user password</param>
        /// <param name="isLocal">Whether the impersonated user is local to this server</param>
        /// <returns>The FileInfo for the specified file</returns>
        public virtual FDCFileInfo GetFileInfo(string file, string user, string password, bool isLocal)
        {
            Impersonation impersonated = null;
            FileInfo      fi           = null;

            try
            {
                if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(password))
                {
                    impersonated = new Impersonation();
                    impersonated.Impersonate(user, password, !isLocal);
                }

                if (File.Exists(file))
                {
                    fi = new FileInfo(file);
                }
            }
            finally
            {
                if (impersonated != null)
                {
                    impersonated.UnImpersonate();
                    impersonated = null;
                }
            }

            if (fi == null)
            {
                return(null);
            }

            return(new FDCFileInfo {
                CreationTimeUtc = fi.CreationTimeUtc, LastAccessTimeUtc = fi.LastAccessTimeUtc, LastWriteTimeUtc = fi.LastWriteTimeUtc, Size = fi.Length
            });;
        }
        /// <summary>
        /// An impersonation safe way to get DirectoryInfo for this DeploymentController.
        /// </summary>
        /// <param name="directory">The directory for which DirectoryInfo is being requested</param>
        /// <param name="user">The user to impersonate</param>
        /// <param name="password">The impersonated user password</param>
        /// <param name="isLocal">Whether the impersonated user is local to this server</param>
        /// <returns>The FileInfo for the specified file</returns>
        public virtual FDCDirectoryInfo GetDirectoryInfo(string directory, string user, string password, bool isLocal)
        {
            Impersonation impersonated = null;
            DirectoryInfo di           = null;

            try
            {
                if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(password))
                {
                    impersonated = new Impersonation();
                    impersonated.Impersonate(user, password, !isLocal);
                }

                if (Directory.Exists(directory))
                {
                    di = new DirectoryInfo(directory);
                }
            }
            finally
            {
                if (impersonated != null)
                {
                    impersonated.UnImpersonate();
                    impersonated = null;
                }
            }

            if (di == null)
            {
                return(null);
            }

            return(new FDCDirectoryInfo {
                CreationTimeUtc = di.CreationTimeUtc, LastAccessTimeUtc = di.LastAccessTimeUtc, LastWriteTimeUtc = di.LastWriteTimeUtc
            });;
        }
Ejemplo n.º 21
0
 void ImpersonateWindowsContext()
 {
     objImp = new Impersonation(_LDAPUser, _LDAPPassword, _LDAPDomainName);
     objImp.Impersonate();
 }
Ejemplo n.º 22
0
  void ImpersonateWindowsContext()
 {
     objImp = new Impersonation(_LDAPUser, _LDAPPassword, _LDAPDomainName);
     objImp.Impersonate();
 }
        protected bool GoodDirectory(string dir)
        {
            try
            {
                if (CheckDirectoryExists)
                {
                    if (!_LastTouched.ContainsKey(dir))
                    {
                        _LastTouched[dir] = new Touched {
                            Exists = false, LastAttempt = DateTime.MinValue
                        }
                    }
                    ;

                    if ((DateTime.UtcNow - _LastTouched[dir].LastAttempt).TotalSeconds > 180 || _LastTouched[dir].Exists)
                    {
                        if (!_LastTouched[dir].Exists)
                        {
                            if (DestinationPingable && !STEM.Sys.IO.Net.PingHost(STEM.Sys.IO.Path.IPFromPath(dir)))
                            {
                                _LastTouched[dir].LastAttempt = DateTime.UtcNow;
                                return(false);
                            }
                        }

                        if (!String.IsNullOrEmpty(DestinationPathUser) && !String.IsNullOrEmpty(DestinationPathPassword))
                        {
                            STEM.Sys.Security.Impersonation impersonation = new Impersonation();

                            try
                            {
                                impersonation.Impersonate(DestinationPathUser, DestinationPathPassword, DestinationPathImpersonationIsLocal);

                                if (DirectoryExists(dir))
                                {
                                    _LastTouched[dir].Exists = true;
                                }
                                else
                                {
                                    _LastTouched[dir].Exists = false;
                                }
                            }
                            finally
                            {
                                impersonation.UnImpersonate();
                            }
                        }
                        else
                        {
                            if (DirectoryExists(dir))
                            {
                                _LastTouched[dir].Exists = true;
                            }
                            else
                            {
                                _LastTouched[dir].Exists = false;
                            }
                        }

                        _LastTouched[dir].LastAttempt = DateTime.UtcNow;
                    }

                    return(_LastTouched[dir].Exists);
                }
                else
                {
                    return(true);
                }
            }
            catch { }

            return(false);
        }
        public override bool Validate()
        {
            // TODO failures in create and cleanup should be ignored for couple of times
            // TODO Add retries in validation logic
            // TODO talk to guest agent and gets it version and validate if latest
            object t = Impersonation.Impersonate(ConfigurationManager.UserName, ConfigurationManager.Password);

            try
            {
                var token      = AzureHelper.GetAccessTokenAsync();
                var credential = new TokenCredentials(token.Result.AccessToken);

                PublicIPAddress ipAddress = AzureHelper.GetPublicAddressAsync(credential, groupName, subscriptionId, "myPublicIP").Result;

                // TODO: make username-password at one place instead of at both ARM and here
                SecureString securePwd = new SecureString();
                password.ToCharArray().ToList().ForEach(p => securePwd.AppendChar(p));

                // this is the entrypoint to interact with the system (interfaced for testing).
                var remoteComputer = new Uri(string.Format("{0}://{1}:5986", "https", ipAddress.IpAddress));

                var connection = new WSManConnectionInfo(remoteComputer, String.Empty, new PSCredential(username, securePwd));

                var option = new PSSessionOption();
                option.SkipCACheck         = true;
                option.SkipCNCheck         = true;
                option.SkipRevocationCheck = true;
                connection.SetSessionOptions(option);

                connection.AuthenticationMechanism = AuthenticationMechanism.Negotiate;

                // TODO What if powershell session gets stuck in between

                var runspace = RunspaceFactory.CreateRunspace(connection);
                runspace.Open();

                var powershell = PowerShell.Create();
                powershell.Runspace = runspace;

                powershell.AddScript("get-psdrive –psprovider filesystem");
                var results = powershell.Invoke();
                foreach (var output in results.Where(o => o != null))
                {
                }

                bool ifCustomData = true;
                if (!string.IsNullOrWhiteSpace(customData))
                {
                    powershell.AddScript("Get-Content C:\\AzureData\\CustomData.bin -Encoding UTF8");
                    results      = powershell.Invoke();
                    ifCustomData = (results.Where(o => o != null).ToList().Count == 1);
                    foreach (var output in results.Where(o => o != null))
                    {
                        logger.Info(string.Format("Expected: {0} Actual: {1}", customData, output));
                        ifCustomData &= (output.ToString() == customData);
                    }
                }

                runspace.Close();

                if (!ifCustomData)
                {
                    throw new ArgumentException("Incorrect custom data!!");
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
                return(false);
            }
            finally
            {
                Impersonation.UndoImpersonation(t);
            }

            return(true);
        }