Provides a mechanism for impersonating a user. This is intended to be disposable, and used in a using ( ) block.
Inheritance: IDisposable
Example #1
0
        /// <summary>
        /// Deletes the specified directory and, if indicated,
        /// any subdirectories and files in the directory.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="user">The user.</param>
        /// <param name="recursive">if set to <c>true</c> [recursive].</param>
        /// <param name="debug">if set to <c>true</c> [debug].</param>
        /// <returns></returns>
        public static FileOperationResult DeleteDirectory(string path,
                                                          DomainUser user, bool recursive = false, bool debug = false)
        {
            FileOperationResult result;

            // ReSharper disable once UnusedVariable
            using (
                var impersonation = new Impersonation(user.Domain, user.Name,
                                                      user.Pwd, ImpersonationLevel.Delegation))
            {
                if (Directory.Exists(path))
                {
                    try
                    {
                        Directory.Delete(path, recursive);
                        result = new FileOperationResult(path,
                                                         FileOperation.Delete, true);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                        result = new FileOperationResult(path,
                                                         FileOperation.Delete, ex);
                    }
                }
                else
                {
                    result = new FileOperationResult(path,
                                                     FileOperation.Delete, false, "Directory not Found");
                }
            }
            return(result);
        }
 public void Impersonation_Tests()
 {
     using (var impersonation = new Impersonation(Domain, Username, Password))
     {
         Assert.IsNotNull(impersonation);
     }
 }
Example #3
0
        public WSUS()
        {
            // I use impersonation to use other logon than mine. Remove the following "using" if not needed
            using (Impersonation.LogonUser("mydomain.local", "admin_account_wsus", "Password", LogonType.Batch))
            {
                ComputerTargetScope      scope   = new ComputerTargetScope();
                IUpdateServer            server  = AdminProxy.GetUpdateServer("wsus_server.mydomain.local", false, 80);
                ComputerTargetCollection targets = server.GetComputerTargets(scope);
                // Search
                targets = server.SearchComputerTargets("any_server_name_or_ip");

                // To get only on server FindTarget method
                IComputerTarget target = FindTarget(targets, "any_server_name_or_ip");
                Console.WriteLine(target.FullDomainName);
                IUpdateSummary summary      = target.GetUpdateInstallationSummary();
                UpdateScope    _updateScope = new UpdateScope();
                // See in UpdateInstallationStates all other properties criteria
                _updateScope.IncludedInstallationStates = UpdateInstallationStates.Downloaded;
                UpdateInstallationInfoCollection updatesInfo = target.GetUpdateInstallationInfoPerUpdate(_updateScope);

                int updateCount = updatesInfo.Count;

                foreach (IUpdateInstallationInfo updateInfo in updatesInfo)
                {
                    Console.WriteLine(updateInfo.GetUpdate().Title);
                }
            }
        }
Example #4
0
        public ActionResult Services(string serviceNameParam, int?id)
        {
            ServiceViewModel service = new ServiceViewModel(serviceNameParam);

            var credentials = new UserCredentials(service.Username, service.Password);

            Impersonation.RunAsUser(credentials, SimpleImpersonation.LogonType.Interactive, () =>
            {
                ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, service.Server, service.Name);
                scp.Assert();

                ServiceController sc = new ServiceController(service.Name, service.Server);
                TimeSpan timeout     = new TimeSpan(0, 0, 30);
                switch (id)
                {
                case 0:
                    sc.Stop();
                    sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                    break;

                case 1:
                    sc.Start();
                    sc.WaitForStatus(ServiceControllerStatus.Running, timeout);
                    break;

                default:
                    service.Status = sc.Status.ToString();
                    break;
                }
            });
            return(View(service));
        }
 public void ThenImpersonateFails()
 {
     // Act / Assert
     Assert.Throws <InvalidOperationException>(
         () =>
         Impersonation.Impersonate(this._user, this._password));
 }
Example #6
0
        public override FileInfo GetFileInfo(string file)
        {
            Impersonation token = null;

            try
            {
                Impersonate(out token);

                if (System.IO.File.Exists(file))
                {
                    System.IO.FileInfo i = new System.IO.FileInfo(file);
                    return(new FileInfo {
                        CreationTimeUtc = i.CreationTimeUtc, LastAccessTimeUtc = i.LastAccessTimeUtc, LastWriteTimeUtc = i.LastWriteTimeUtc, Size = i.Length
                    });
                }
            }
            catch
            {
            }
            finally
            {
                Unimpersonate(token);
            }

            return(null);
        }
Example #7
0
        public override void DeleteDirectory(string directory, bool recurse, bool deleteFiles)
        {
            Impersonation token = null;

            try
            {
                Impersonate(out token);

                if (System.IO.Directory.Exists(directory))
                {
                    if (!deleteFiles)
                    {
                        if (STEM.Sys.IO.Directory.STEM_GetFiles(directory, "*", "*", recurse ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly, false).Count > 0)
                        {
                            throw new System.IO.IOException(directory + " contains files and deleteFiles is false.");
                        }
                    }

                    System.IO.Directory.Delete(directory, recurse);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Unimpersonate(token);
            }
        }
Example #8
0
        /// <summary>
        /// Read contents as string for a single file. See: https://github.com/FrendsPlatform/Frends.File
        /// </summary>
        /// <returns>Object {string FilePath }  </returns>
        public static Result DownloadFile([PropertyTab] Parameters parameters, [PropertyTab] Options options)
        {
            using (var webClient = new WebClient())
            {
                if (parameters.Headers != null)
                {
                    foreach (var header in parameters.Headers)
                    {
                        webClient.Headers.Add(header.Name, header.Value);
                    }
                }

                if (options.AllowInvalidCertificate)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
                }

                if (options.UseGivenUserCredentialsForRemoteConnections)
                {
                    var domainAndUserName = GetDomainAndUserName(options.UserName);
                    Impersonation.RunAsUser(new UserCredentials(domainAndUserName[0], domainAndUserName[1], options.Password), LogonType.NewCredentials, () => webClient.DownloadFile(parameters.Address, parameters.DestinationFilePath));
                }
                else
                {
                    webClient.DownloadFile(parameters.Address, parameters.DestinationFilePath);
                }
            }

            return(new Result()
            {
                FilePath = parameters.DestinationFilePath
            });
        }
    public ICustomActivityResult Execute() {
      if (string.IsNullOrEmpty(Username)) {
        Directory.Exists(SourcePath);
        Console.WriteLine("The Folder does Exist", SourcePath);
      } else {
        var networkUser = Username.Split('\\');
        if (networkUser.Length < 2) throw new Exception("username must be in the \"Domain\\Username\" format");

        var userCredentials = new UserCredentials(networkUser[0], networkUser[1], Password);
        Impersonation.RunAsUser(userCredentials, LogonType.NewCredentials, () => {
        if (Result == "False") {
            try {
              FileInfo fi = new FileInfo(SourcePath);
              if (fi.Exists) {
                fi.Delete();
              } else {
                var networkUser = Username.Split('\\');
                var userCredentials = new UserCredentials(networkUser[0], networkUser[1], Password);
                Impersonation.RunAsUser(userCredentials, LogonType.NewCredentials, () =>{
                  try {
                    FileInfo fi = new FileInfo(SourcePath);
                    if (fi.Exists) {
                      fi.Delete();
                    }
                  }
                  catch(Exception e) {
                    Console.WriteLine(e.Message);
                  }

        });
      }
    }
  }
}
        public void UpdateFile(string path)
        {
            if (OperationCredential != null)
            {
                var credentials = new UserCredentials(OperationCredential.Domain, OperationCredential.UserName, OperationCredential.Password);


                var result = Impersonation.RunAsUser(credentials, LogonType.Interactive, () =>
                {
                    // do whatever you want as this user.
                    using (StreamWriter streamWriter = new StreamWriter(path, false))
                    {
                        streamWriter.WriteLine(DateTime.Now.ToString());
                    }

                    return("OK");
                });
            }
            else
            {
                using (StreamWriter streamWriter = new StreamWriter(path, false))
                {
                    streamWriter.WriteLine(DateTime.Now.ToString());
                }
            }
        }
Example #11
0
        /*
         * Uses the Config system to get the specified configuraiton
         *
         * The following method is the only accessors to the config system,
         * and it wraps config exceptions with an explanatory HTTP
         * exception with an error formatter. It also makes sure the client
         * is not impersonated while accessing the config system.
         */
        private HttpConfigurationRecord GetCompleteConfigRecord(String reqpath, IHttpMapPath configmap)
        {
            HttpConfigurationRecord configrecord = null;

            HttpContext.ImpersonationSuspendContext ictx = Impersonation.SuspendIfClient();

            try {
                try {
                    if (reqpath == null || reqpath.Length == 0 || HttpRuntime.IsPathWithinAppRoot(reqpath))
                    {
                        // lookup by path
                        using (new HttpContextWrapper(this)) {
                            configrecord = HttpConfigurationSystem.GetComplete(reqpath, _wr);
                        }
                    }
                    else
                    {
                        // if the path is outside of the application (and not site or machine)
                        // then use application config
                        configrecord = HttpConfigurationSystem.GetCompleteForApp();
                    }
                }
                finally {
                    ictx.Resume();
                }
            }
            catch { // Protect against exception filters
                throw;
            }

            return(configrecord);
        }
        /// <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>());
        }
        /// <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;
                    }
                }
            }
        }
        /// <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);
        }
        // TODO-osy: Use Entity Framework
        public IList <Contact> FindAccountContacts(string accountId)
        {
            const string storedProcedureName = "sp_findAccountContacts";
            var          contacts            = new List <Contact>();

            // IMPORTANT: You have to use LogonType.NewCredentials!!!
            // http://stackoverflow.com/questions/559719/windows-impersonation-from-c-sharp
            using (var impersonation = Impersonation.LogonUser(DOMAIN, USERNAME, PASSWORD, LogonType.NewCredentials))
            {
                using (DbConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    using (DbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = storedProcedureName;
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.Parameters.Add(new SqlParameter("@accountID", accountId));
                        using (var dataReader = command.ExecuteReader())
                        {
                            while (dataReader.Read())
                            {
                                var contact = new Contact();
                                contact.ContactId   = Convert.ToString(dataReader["contactID"]);
                                contact.FirstName   = Convert.ToString(dataReader["firstName"]);
                                contact.LastName    = Convert.ToString(dataReader["lastName"]);
                                contact.ContactType = Convert.ToString(dataReader["contactType"]);
                                contact.Function    = Convert.ToString(dataReader["function"]);
                                contacts.Add(contact);
                            }
                        }
                    }
                }
            }
            return(contacts);
        }
Example #17
0
        private Impersonation GetImpersonation(Impersonation request)
        {
            var           id    = request?.Id;
            Impersonation ret   = null;
            var           query = DocQuery.ActiveQuery ?? Execute;

            DocPermissionFactory.SetSelect <Impersonation>(currentUser, "Impersonation", request.Select);

            DocEntityImpersonation entity = null;

            if (id.HasValue)
            {
                entity = DocEntityImpersonation.Get(id.Value);
            }
            if (null == entity)
            {
                throw new HttpError(HttpStatusCode.NotFound, $"No Impersonation found for Id {id.Value}");
            }

            if (!DocPermissionFactory.HasPermission(entity, currentUser, DocConstantPermission.VIEW))
            {
                throw new HttpError(HttpStatusCode.Forbidden, "You do not have VIEW permission for this route.");
            }

            ret = entity?.ToDto();
            return(ret);
        }
        public void DeleteFile(string path)
        {
            bool fileExists = File.Exists(path);

            if (OperationCredential != null)
            {
                var credentials = new UserCredentials(OperationCredential.Domain, OperationCredential.UserName, OperationCredential.Password);

                var result = Impersonation.RunAsUser(credentials, LogonType.Interactive, () =>
                {
                    if (fileExists)
                    {
                        // do whatever you want as this user.
                        System.IO.File.Delete(path);
                    }

                    return("OK");
                });
            }
            else
            {
                if (fileExists)
                {
                    // do whatever you want as this user.
                    try
                    {
                        System.IO.File.Delete(path);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
Example #19
0
 static void Main(string[] args)
 {
     using (var impersonation = new Impersonation("domain", "username", "password", ImpersonationLevel.Delegation))
     {
         // Do remote operations here.
     }
 }
        private void LocalStartService()
        {
            Program.Logger.Log.Info("Start the service");

            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            var appprincipal = Thread.CurrentPrincipal as WindowsPrincipal;

            Program.Logger.Log.Info($"Is in administrators: {appprincipal.IsInRole("Administrators")}");
            Program.Logger.Log.Info($"Windows identity: {WindowsIdentity.GetCurrent().Name}"); //Windows identity: NT AUTHORITY\SYSTEM

            LogSystemInfo();
            WriteExecutingAssemblyVersion();

#if !DEBUG
            using (var impersonation = new Impersonation(BuiltinUser.NetworkService))
            {
#endif
            try
            {
                SDKEnvironment.Initialize();    // General initialize. Always required
                SDKEnvironment.RemoveAllServers();
                TryConnectingToMilestoneServer();
            }
            catch (Exception ex)
            {
                Program.Logger.Log.Error(null, ex);
                Program.Logger.Log.Info($"Windows identity: {WindowsIdentity.GetCurrent().Name}");     //Windows identity: NT AUTHORITY\NETWORK SERVICE
            }
#if !DEBUG
        }
#endif
        }
Example #21
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();
            }
        }
Example #22
0
 public Interaction(Logging log, Config config, Impersonation impersonation, QueryBuild queryBuild)
 {
     _log           = log;
     _configModel   = config.Get();
     _impersonation = impersonation;
     _queryBuild    = queryBuild;
 }
Example #23
0
 public Extract(Logging log, Config config, Impersonation impersonation)
 {
     _log           = log;
     _configModel   = config.Get();
     _impersonation = impersonation;
     _parents       = new List <SharedParent>();
 }
Example #24
0
        static void Main(string[] args)
        {
            var parsedResult = Parser.Default.ParseArguments <Options>(args);

            parsedResult.WithParsed(options =>
            {
                try
                {
                    using (Impersonation.LogonUser(options.Domain, options.Username, options.Password, LogonType.Interactive))
                    {
                        var process = new Process();
                        process.StartInfo.FileName  = options.Command;
                        process.StartInfo.Arguments = options.Arguments;
                        process.Start();
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            });

            parsedResult.WithNotParsed((error) =>
            {
                Console.ReadKey();
            });
        }
Example #25
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 List <ActionResult> CopyLocalToRemote(ILog log, Dictionary <string, byte[]> destFiles)
 {
     if (_credentials == null)
     {
         // cannot impersonate without credentials, attempt as current user
         var results = PerformFileWrites(log, destFiles);
         return(results);
     }
     else
     {
         // write new files as destination user
         try
         {
             var results = new List <ActionResult>();
             Impersonation.RunAsUser(_credentials, _defaultLogonType, () =>
             {
                 results = PerformFileWrites(log, destFiles);
             });
             return(results);
         }
         catch (Exception exp)
         {
             return(new List <ActionResult> {
                 new ActionResult(exp.Message, false)
             });
         }
     }
 }
Example #27
0
        public override DirectoryInfo GetDirectoryInfo(string directory)
        {
            Impersonation token = null;

            try
            {
                Impersonate(out token);

                if (System.IO.Directory.Exists(directory))
                {
                    System.IO.DirectoryInfo i = new System.IO.DirectoryInfo(directory);
                    return(new DirectoryInfo {
                        CreationTimeUtc = i.CreationTimeUtc, LastAccessTimeUtc = i.LastAccessTimeUtc, LastWriteTimeUtc = i.LastWriteTimeUtc
                    });
                }
            }
            catch
            {
            }
            finally
            {
                Unimpersonate(token);
            }

            return(null);
        }
Example #28
0
        /// <summary>
        /// Deletes the file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="user">The user.</param>
        /// <param name="debug">if set to <c>true</c> [debug].</param>
        /// <returns></returns>
        public static FileOperationResult DeleteFile(FileInfo file,
                                                     DomainUser user, bool debug = false)
        {
            FileOperationResult result;

            // ReSharper disable once UnusedVariable
            using (
                var impersonation = new Impersonation(user.Domain, user.Name,
                                                      user.Pwd, ImpersonationLevel.Delegation))
            {
                try
                {
                    File.Delete(file.FullName);
                    result = new FileOperationResult(file.FullName,
                                                     FileOperation.Delete, true);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    result = new FileOperationResult(file.FullName,
                                                     FileOperation.Delete, ex);
                }
            }
            return(result);
        }
Example #29
0
        private static void EnsureUserSession(int pid, string[] argv)
        {
            if (WindowsIdentity.GetCurrent().IsSystem)
            {
                uint targetSessionID = uint.MaxValue;

                IntPtr userToken = IntPtr.Zero;

                // Retrieves the target process Session ID
                try
                {
                    using (Process srcPr = Process.GetProcessById(pid))
                    {
                        targetSessionID = (uint)srcPr.SessionId;
                    }
                }
                catch (ArgumentException)
                {
                    LogHelper.Warning("Unable to retrieve the target process SessionID. Process may have already exited.");
                    targetSessionID = uint.MaxValue;
                }

                // If the target Session ID is still unknown or if it belongs to SYSTEM, or the session doesn't work, the currently active session is retrieved.
                if (targetSessionID == uint.MaxValue || targetSessionID == 0 || (!CommonHelper.WTSQueryUserToken(targetSessionID, ref userToken)))
                {
                    targetSessionID = CommonHelper.WTSGetActiveConsoleSessionId();
                    if (targetSessionID == 0xFFFFFFFF)
                    {
                        throw new Exception("No active session found. Aborting.");
                    }

                    // If the active Session ID is still a SYSTEM one, cannot continue.
                    if (targetSessionID == 0)
                    {
                        throw new Exception("WFN can not start in the SYSTEM session.");
                    }

                    // Because the target Session ID is found, impersonation can take place.
                    if (!CommonHelper.WTSQueryUserToken(targetSessionID, ref userToken))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to retrieve the current user token.");
                    }
                }

                try
                {
                    string argstr = String.Join(" ", argv.Select(a => a.Contains(" ") ? "\"" + a + "\"" : a).ToArray()) + " -impersonated 1";
                    LogHelper.Debug("Impersonating. Parameters: " + argstr);

                    Impersonation.LaunchProcessAsUser(Process.GetCurrentProcess().MainModule.FileName, argstr, userToken);
                }
                finally
                {
                    CloseHandle(userToken);
                }

                Environment.Exit(0);
            }
        }
Example #30
0
 public void RunAction(Action action)
 {
     if (_poshCredential != null)
     {
         Impersonation.RunAsUser(_poshCredential.UserCredentials, _poshCredential.LogonType, action);
     }
     action();
 }
 public ActionResult UserApprove(Guid id)
 {
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     UploadedFormat31File uploadedFormat31File = _repository.Fetch<UploadedFormat31File>().Where(p => p.uploadedFormat31FileId == id).First();
     if (uploadedFormat31File == null)
     {
         return HttpNotFound();
     }
     ICollection<Format31FileData> fileData = _repository.Fetch<Format31FileData>().Where(f => f.uploadedFormat31FileId == id).OrderBy(f => f.index).ToList();
     uploadedFormat31File.fileData = fileData;
     try
     {   //Check that file has not been sent before
         //Generate Format 31 File
         //var fileName = uploadedFormat31File.fileName.ToString();
         var fileName = "F" + uploadedFormat31File.batchNumber + "." + uploadedFormat31File.extension;
         if (!Directory.Exists(HttpContext.Server.MapPath("~/Files/format31/generatedF31")))
         {
             Directory.CreateDirectory(HttpContext.Server.MapPath("~/Files/format31/generatedF31"));
         }
         var fullLocalFilePath = Path.Combine(Server.MapPath("~/Files/format31/generatedF31"), fileName + "_" + DateTime.Now.ToFileTime());
         string contents = Format31Generator.generateFormat31(uploadedFormat31File);
         System.IO.File.WriteAllText(fullLocalFilePath, contents);
         //Fetch send credentials
         var impersonationCredentials = new ImpersonationCred();
         impersonationCredentials.domain = _repository.Fetch<Parameter>().Where(b=>b.Paramname=="ImpersonationDomain").First().Paramvalue;
         impersonationCredentials.username = _repository.Fetch<Parameter>().Where(b=>b.Paramname=="ImpersonationUser").First().Paramvalue;
         Parameter impersonationPasswordParam = _repository.Fetch<Parameter>().Where(b=>b.Paramname=="").First();
         impersonationCredentials.password = StringCipher.Decrypt(impersonationPasswordParam.Paramvalue, "S41T" + impersonationPasswordParam.Osysdate.ToString() + "Th@tS3cr3tS@uc3");
         impersonationCredentials.path = _repository.Fetch<Parameter>().Where(b=>b.Paramname=="ImpersonationPathF31").First().Paramvalue;
         string fullDestinationPath = Path.Combine(impersonationCredentials.path, fileName);
         //Send
         Impersonation impersonation = new Impersonation();
         impersonation.fnSecureCopy(fullLocalFilePath, fullDestinationPath, impersonationCredentials);
         //Update the status of the format31 file and save to db
         uploadedFormat31File.Cheker = User.Identity.GetUserName();
         uploadedFormat31File.StatusOptions = MyEnums.StatusOptions.Approved;
         //db.UploadedFormat31File.Attach(uploadedFormat31File);
         db.Entry(uploadedFormat31File).State = EntityState.Modified;
         db.SaveChanges();
         _sharedCls.LogAudit(User.Identity.GetUserName(), "Approve", Request.UserHostName, "Approved Format31 File", "Approval", "Format31");
     }
     catch (Exception e)
     {
         _logs.LogError(User.Identity.GetUserName(), "RegisterUser", "Format31.UserApprove: " + e.Message,
      Request.ServerVariables["REMOTE_ADDR"], HttpContext.Server.MapPath("."), "Format31");
         System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/errorLOG.txt"), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
         System.IO.StreamWriter s = new System.IO.StreamWriter(fs);
         s.BaseStream.Seek(0, System.IO.SeekOrigin.End);
         s.WriteLine("ERROR DATE: " + System.DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture) + " \nERROR MESSAGE: " + e.Message + "\nSOURCE: " + e.Source + "\nFORM NAME: " + System.Web.HttpContext.Current.Request.Url.ToString() + "\nQUERYSTRING: " + Request.QueryString.ToString() + "\nTARGETSITE: " + e.TargetSite.ToString() + "\nSTACKTRACE: " + e.StackTrace + System.Diagnostics.EventLogEntryType.Error);
         s.WriteLine("-------------------------------------------------------------------------------------------------------------");
         s.Close();
     }
     return RedirectToAction("ApproveIndex");
 }
Example #32
0
        public static bool CopyFolder(string from, string to, DateTime logTime, string name ,EnumsBackupType backuptype,   long Schedule_DetailId ,string SourceUserId , string sourceUserPassword, string sourceuserdomain, string TargetUserid, string TargetUserPassword, string targetuserdomain)
        {
            var imporsonate = new Impersonation(targetuserdomain, TargetUserid, TargetUserPassword.Trim());

            try
            {
                using (imporsonate)

                {
                    Log.Begin(name + ": Backup started ...", Schedule_DetailId);

                    if (!Directory.Exists(from))
                    {
                        imporsonate.undoImpersonation();
                        Log.Error(name + ": Source Folder does not exist or access denied to " + from, Schedule_DetailId);
                        throw new Exception("Source Folder does not exist or access denied to " + from);
                    }

                    if ((backuptype == EnumsBackupType.Incremental_Backup))
                    {
                        if (!Directory.Exists(to))
                            Directory.CreateDirectory(to);

                        to = to + "\\" + name + "-" + logTime.ToString("MM-dd-yyyy");

                        Directory.CreateDirectory(to);

                    }
                    else if (!Directory.Exists(to))
                    {
                        Directory.CreateDirectory(to);
                    }

                    string[] directories = Directory.GetDirectories(from, "*.*", SearchOption.AllDirectories);

                    Parallel.ForEach(directories, dirPath =>
                    {
                        try
                        {
                            Directory.CreateDirectory(dirPath.Replace(from, to));
                        }
                        catch (Exception ex)
                        {

                            Log.Error(name + ": " + ex.Message, Schedule_DetailId);
                        }
                    });

                    string[] files = Directory.GetFiles(from, "*.*", SearchOption.AllDirectories);

                    Parallel.ForEach(files, filePath =>
                    {
                        try
                        {
                            //Replace File.Copy to FileStream to prevent source file lock
                            //File.Copy(filePath, filePath.Replace(from, to));

                            using (FileStream source = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                using (FileStream dest = new FileStream(filePath.Replace(from, to), FileMode.Create, FileAccess.ReadWrite))
                                {
                                    source.CopyTo(dest);
                                }
                            }
                        }
                        catch (Exception ex)
                        {

                            Log.Error(name + ": " + ex.Message, Schedule_DetailId);

                        }
                    });

                    Log.End(name + ":  Backup completed successfully", Schedule_DetailId);
                    imporsonate.undoImpersonation();
                    return true;
                }
                //else
                //{
                //    Log.Error(name + ": Target User not authenticated " ,  Schedule_DetailId);
                //    return false; }

            }
            catch (Exception ex)
            {
                Log.Error(name + ": " + ex.Message, Schedule_DetailId);
                Log.End  (name + ":  Backup completed with errors", Schedule_DetailId);
                imporsonate.undoImpersonation();
                return false;
            }
        }
Example #33
0
        public ActionResult ReportLogApprove(Guid id)
        {
            var model = _repository.Find<REPORTLOG>(id);

            REPORTLOG report=_repository.Fetch<REPORTLOG>().Where(p=>p.Id == id).First();
            string fileLocation = HttpContext.Server.MapPath(".") + @"\AuditorSelect\Uploads\" ;
                    if (!Directory.Exists(HttpContext.Server.MapPath(".") + @"\AuditorSelect\Uploads\"))
                    {
                        Directory.CreateDirectory(HttpContext.Server.MapPath(".") + @"\AuditorSelect\Uploads\");
                    }
            format.FnF31Two(report, fileLocation);
            var batch = _repository.Fetch<Parameter>().FirstOrDefault(p => p.Paramname == "BatchNo").Paramvalue;
            string cpyFile = fileLocation + @"\F" + batch + ".000";
            var impersonationCredentials = new ImpersonationCred();
            impersonationCredentials.domain = db.Parameter.Where(b => b.Paramname == "ImpersonationDomain").First().Paramvalue;
            impersonationCredentials.username = db.Parameter.Where(b => b.Paramname == "ImpersonationUser").First().Paramvalue;
            Parameter impersonationPasswordParam = db.Parameter.Where(b => b.Paramname == "ImpersonationPassword").First();
            impersonationCredentials.password = StringCipher.Decrypt(impersonationPasswordParam.Paramvalue, "S41T" + impersonationPasswordParam.Osysdate.ToString() + "Th@tS3cr3tS@uc3");
            impersonationCredentials.path = db.Parameter.Where(b => b.Paramname == "ImpersonationPathAudit").First().Paramvalue;
            //Send

            //if (!Directory.Exists(Path.GetDirectoryName(@"D:\AuditLetter" + @"\" + Path.GetFileName(cpyFile))))
            //    Directory.CreateDirectory(Path.GetDirectoryName(@"D:\AuditLetter" + @"\" + Path.GetFileName(cpyFile)));

            //System.IO.File.Copy(cpyFile, @"D:\AuditLetter" + @"\" + Path.GetFileName(cpyFile), true);

            Impersonation impersonation = new Impersonation();
            impersonation.fnSecureCopy(cpyFile, impersonationCredentials.path + @"\" + Path.GetFileName(cpyFile), impersonationCredentials);
            model.State = MyEnums.StatusOptions.Approved;
            model.ReportChecker = User.Identity.GetUserName();
            model.Charged = true;
            _repository.SaveUpdate(model);
            getVals.LogAudit(User.Identity.GetUserName(), "Approved", Request.UserHostName, "Approved Generated Audit Report. Report Name" + model.ReportName, "Approved", "AuditLetters");
            return RedirectToAction("ReportLogIndex");
        }
Example #34
0
  void ImpersonateWindowsContext()
 {
     objImp = new Impersonation(_LDAPUser, _LDAPPassword, _LDAPDomainName);
     objImp.Impersonate();
 }
Example #35
0
        static void Main()
        {
            using (var i = new Impersonation("igsdomain", "jolmos", "JPol.291179"))
            {
                var connection = new HubConnection("http://localhost:34080/");
                connection.Credentials = CredentialCache.DefaultCredentials;
                var hub = connection.CreateHubProxy("LogsHub");

                connection.Start().Wait();
                //.ContinueWith(task =>
                //{
                //    if (task.IsFaulted)
                //    {
                //        Console.WriteLine("There was an error opening the connection:{0}",
                //                          task.Exception.GetBaseException());
                //        Console.ReadLine();
                //        Environment.Exit(1);
                //    }
                //    else
                //    {
                //        Console.WriteLine("Connected");
                //    }
                //}).Wait();

                var hardCodedGuid = new Guid("63ff8081-b43b-474a-a493-f8c3534f7324");
                var existingLogMessageId = new Guid("60D8E681-BE51-4934-B883-28037E6CC328");
                var ff = new Guid("011CCAB6-D901-469B-9DDC-15E08383CCE7");

                //.ContinueWith(task =>
                //{
                //    if (task.IsFaulted)
                //    {
                //        Console.WriteLine("There was an error calling send: {0}",
                //                          task.Exception.GetBaseException());
                //    }
                //    else
                //    {
                //        Console.WriteLine("done");
                //    }
                //}).RunSynchronously();

                hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel
                {
                    LogMessageId = Guid.NewGuid(),
                    Message = "1",
                    DeploymentLogId = hardCodedGuid,
                    TimeStamp = DateTime.Now
                }).Wait();

                hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel
                {
                    LogMessageId = existingLogMessageId,
                    Message = "2",
                    DeploymentLogId = hardCodedGuid,
                    TimeStamp = DateTime.Now
                }).Wait();

                hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel
                {
                    LogMessageId = ff,
                    Message = "3",
                    DeploymentLogId = hardCodedGuid,
                    TimeStamp = DateTime.Now
                }).Wait();

                hub.Invoke("NewLog", hardCodedGuid.ToString(), new LogMessageModel
                {
                    LogMessageId = Guid.NewGuid(),
                    Message = "4",
                    DeploymentLogId = hardCodedGuid,
                    TimeStamp = DateTime.Now
                }).Wait();


                //hub.On<string>("NewLog",
                //    (name) => Console.WriteLine("{0} - {1}", name));

                Console.Read();

                connection.Stop();

            }
        }
Example #36
0
        private void fnHandoffs(StringBuilder entry, string branch, string filepath)
        {
            string date = DateTime.Now.ToString("yyyyMMdd");
            filepath += date + @"\IF_PEBS_RFRTUPL_" + branch + DateTime.Now.ToString("yyMMdd.DAT");
            if (File.Exists(filepath))
                File.Delete(filepath);
            if (!Directory.Exists(Path.GetDirectoryName(filepath)))
                Directory.CreateDirectory(Path.GetDirectoryName(filepath));
            FileStream fs = new FileStream(filepath, FileMode.CreateNew, FileAccess.ReadWrite);
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.Write(entry);
            }
            var impersonationCredentials = new ImpersonationCred();
            impersonationCredentials.domain = db.Parameter.Where(b => b.Paramname == "ImpersonationDomain").First().Paramvalue;
            impersonationCredentials.username = db.Parameter.Where(b => b.Paramname == "ImpersonationUser").First().Paramvalue;
            Dev.Tech.Db.Models.SysConfig.Parameter impersonationPasswordParam = db.Parameter.Where(b => b.Paramname == "ImpersonationPassword").First();
            impersonationCredentials.password = StringCipher.Decrypt(impersonationPasswordParam.Paramvalue, "S41T" + impersonationPasswordParam.Osysdate.ToString() + "Th@tS3cr3tS@uc3");
            impersonationCredentials.path = db.Parameter.Where(b => b.Paramname == "ImpersonationPathPool").First().Paramvalue;
            //Send
            //if (!Directory.Exists(Path.GetDirectoryName(@"D:\PoolFile" + @"\" + Path.GetFileName(filepath))))
            //    Directory.CreateDirectory(Path.GetDirectoryName(@"D:\PoolFile" + @"\" + Path.GetFileName(filepath)));

            //File.Copy(filepath, @"D:\PoolFile" + @"\" + Path.GetFileName(filepath), true);

            Impersonation impersonation = new Impersonation();
            impersonation.fnSecureCopy(filepath, impersonationCredentials.path + @"\" + Path.GetFileName(filepath), impersonationCredentials);
        }