public void Imperson_Upload_Success_Test() { using (var copy = new Impersonator()) { Assert.True(copy.Impersonate(uncDomain, uncUser, uncPassword)); copy.Upload(uncPath, @"D:", @"test.txt"); } }
/// <summary> /// Starts (or reuses) the process resource that is specified by the <see cref="P:System.Diagnostics.Process.StartInfo" /> /// property of this <see cref="T:System.Diagnostics.Process" /> component and associates it with the component. /// </summary> /// <returns>true if a process resource is started; false if no new process resource is started /// (for example, if an existing process is reused).</returns> /// <exception cref="T:System.InvalidOperationException">No file name was specified in the /// <see cref="T:System.Diagnostics.Process" /> component's <see cref="P:System.Diagnostics.Process.StartInfo" />. /// -or- The <see cref="P:System.Diagnostics.ProcessStartInfo.UseShellExecute" /> member of the /// <see cref="P:System.Diagnostics.Process.StartInfo" /> property is true while /// <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardInput" />, /// <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardOutput" />, /// or <see cref="P:System.Diagnostics.ProcessStartInfo.RedirectStandardError" /> is true. /// </exception> /// <exception cref="T:System.ComponentModel.Win32Exception">There was an error in opening the associated file. </exception> /// <exception cref="T:System.ObjectDisposedException">The process object has already been disposed. </exception> public virtual bool Start() { // temporary switch until code is proven to be stable. if (_enableCustomUserLogin) { if (!string.IsNullOrWhiteSpace(StartInfo.Arguments)) { throw new ArgumentException("StartInfo.Arguments is not allowed when starting a process as a user. use ArgumentObject."); } } bool successfulStart = false; if (_enableCustomUserLogin && StartInfo != null && !string.IsNullOrWhiteSpace(StartInfo.UserName)) { using (Impersonator imp = new Impersonator()) { imp.Impersonate(StartInfo.UserName, StartInfo.Domain, StartInfo.Password, StartWithCreateProcessAsUser); successfulStart = true; } } else { _process.StartInfo.Arguments = JsonConvert.SerializeObject(new { name = ArgumentObject["name"], owner = ArgumentObject["owner"], parameters = ArgumentObject.ContainsKey("parameters") ? ArgumentObject["parameters"] : string.Empty }); successfulStart = _process.Start(); } return(successfulStart); }
public void Imperson_Download_Success_Test() { using (var copy = new Impersonator()) { Assert.True(copy.Impersonate(uncDomain, uncUser, uncPassword)); copy.Download(uncPath, @"D:", @"TEST.pdf", "test.pdf"); } }
public void Imperson_DownloadAsBytes_Failed_Test() { using (var copy = new Impersonator()) { Assert.True(copy.Impersonate(uncDomain, uncUser, uncPassword + "s")); var bytes = copy.DownloadAsBytes(uncPath, @"test.pdf"); Assert.AreNotEqual(null, bytes); var destFileName = @"D:" + @"\" + @"test.pdf"; File.WriteAllBytes(@destFileName, bytes); } }
public static bool RunAs(string userName, string domain, string password, Action action) { var result = false; using (var impersonator = new Impersonator()) { if (impersonator.Impersonate(userName, domain, password)) { action?.Invoke(); result = true; } } return(result); }
private void InitializeStorage() { CloudStorageAccount account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("ConfigurationStorageConnectionString")); CloudBlobClient client = account.CreateCloudBlobClient(); CloudBlobContainer dsc = client.GetContainerReference("dsc"); dsc.CreateIfNotExists(); CloudBlockBlob resources = dsc.GetBlockBlobReference("resources.zip"); using (var stream = new MemoryStream()) { resources.DownloadToStream(stream); var tempModulePath = RoleEnvironment.GetLocalResource("Temp").RootPath; var path = DscHelper.PrepareDscResourcePackages(tempModulePath, stream); DscHelper.MoveDscModules(path); } Container = client.GetContainerReference("mof"); Container.CreateIfNotExists(); var blobs = Container.ListBlobs(); try { using (Impersonator.Impersonate()) { foreach (var blob in blobs) { var blobRef = Container.GetBlockBlobReference(blob.Uri.AbsoluteUri); DownloadBlob(blobRef); } } } catch (Exception ex) { Trace.TraceError(ex.Message); } }
private void D3Prefs() { var imp = new Impersonator(); if (Parent.UseWindowsUser) { imp.Impersonate(Parent.WindowsUserName, "localhost", Parent.WindowsUserPassword); } // Copy D3Prefs Logger.Instance.Write("Replacing D3Prefs for user: {0}", Environment.UserName); var currentprefs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Diablo III\D3Prefs.txt"; if (Directory.Exists(Path.GetDirectoryName(currentprefs))) { Logger.Instance.Write("Copy custom D3Prefs file to: {0}", currentprefs); try { File.Copy(Parent.D3PrefsLocation, currentprefs, true); } catch (Exception ex) { Logger.Instance.Write("Failed to copy D3Prefs file: {0}", ex); } } else { Logger.Instance.Write("D3Prefs Failed: Path to \"{0}\" does not exist!", currentprefs); } if (imp != null) { imp.Dispose(); } // Also replace Default User D3Prefs var defaultprefs = Regex.Match(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), string.Format(@"(.+)\\{0}.*", Environment.UserName)).Groups[1].Value; if (Directory.Exists(defaultprefs + "\\Default")) { defaultprefs += "\\Default"; } else if (Directory.Exists(defaultprefs + "\\Default User")) { defaultprefs += "\\Default User"; } else { return; } defaultprefs += @"\Diablo III\D3Prefs.txt"; if (Directory.Exists(Path.GetDirectoryName(defaultprefs))) { Logger.Instance.Write("Copy custom D3Prefs file to: {0}", defaultprefs); try { File.Copy(Parent.D3PrefsLocation, defaultprefs, true); } catch (Exception ex) { Logger.Instance.Write("Failed to copy d3prefs file: {0}", ex); } } Thread.Sleep(1000); }
/// <summary> /// Executes the specified errors. /// </summary> /// <param name="errors">The errors.</param> /// <param name="update"></param> /// <returns></returns> public override Guid Execute(out ErrorResultTO errors, int update) { errors = new ErrorResultTO(); ITestCatalog testCatalog = TstCatalog ?? TestCatalog.Instance; // WorkflowApplicationFactory wfFactor = new WorkflowApplicationFactory(); Guid result = GlobalConstants.NullDataListID; Dev2Logger.Debug("Entered Wf Container"); // Set Service Name DataObject.ServiceName = ServiceAction.ServiceName; // Set server ID, only if not set yet - original server; if (DataObject.ServerID == Guid.Empty) { DataObject.ServerID = HostSecurityProvider.Instance.ServerID; } // Set resource ID, only if not set yet - original resource; if (DataObject.ResourceID == Guid.Empty && ServiceAction?.Service != null) { DataObject.ResourceID = ServiceAction.Service.ID; } // Travis : Now set Data List DataObject.DataList = ServiceAction.DataListSpecification; // Set original instance ID, only if not set yet - original resource; if (DataObject.OriginalInstanceID == Guid.Empty) { DataObject.OriginalInstanceID = DataObject.DataListID; } Dev2Logger.Info($"Started Execution for Service Name:{DataObject.ServiceName} Resource Id:{DataObject.ResourceID} Mode:{(DataObject.IsDebug ? "Debug" : "Execute")}"); //Set execution origin if (!string.IsNullOrWhiteSpace(DataObject.ParentServiceName)) { DataObject.ExecutionOrigin = ExecutionOrigin.Workflow; DataObject.ExecutionOriginDescription = DataObject.ParentServiceName; } else if (DataObject.IsDebug) { DataObject.ExecutionOrigin = ExecutionOrigin.Debug; } else { DataObject.ExecutionOrigin = ExecutionOrigin.External; } ErrorResultTO to = errors; var serviceTestModelTo = testCatalog.FetchTest(DataObject.ResourceID, DataObject.TestName); if (serviceTestModelTo == null) { testCatalog.Load(); serviceTestModelTo = testCatalog.FetchTest(DataObject.ResourceID, DataObject.TestName); } if (serviceTestModelTo == null) { Dev2JsonSerializer serializer = new Dev2JsonSerializer(); var testRunResult = new ServiceTestModelTO { Result = new TestRunResult { TestName = DataObject.TestName, RunTestResult = RunResult.TestInvalid, Message = $"Test {DataObject.TestName} for Resource {DataObject.ServiceName} ID {DataObject.ResourceID}, has been deleted." } }; Dev2Logger.Error($"Test {DataObject.TestName} for Resource {DataObject.ServiceName} ID {DataObject.ResourceID}, has been deleted."); _request.ExecuteResult = serializer.SerializeToBuilder(testRunResult); return(Guid.NewGuid()); } if (serviceTestModelTo.AuthenticationType == AuthenticationType.User) { Impersonator impersonator = new Impersonator(); var userName = serviceTestModelTo.UserName; var domain = ""; if (userName.Contains("\\")) { var slashIndex = userName.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase); domain = userName.Substring(0, slashIndex); userName = userName.Substring(slashIndex + 1); } else if (userName.Contains("@")) { var atIndex = userName.IndexOf("@", StringComparison.InvariantCultureIgnoreCase); userName = userName.Substring(0, atIndex); domain = userName.Substring(atIndex + 1); } var hasImpersonated = impersonator.Impersonate(userName, domain, DpapiWrapper.DecryptIfEncrypted(serviceTestModelTo.Password)); if (!hasImpersonated) { DataObject.Environment.AllErrors.Add("Unauthorized to execute this resource."); DataObject.StopExecution = true; } } else if (serviceTestModelTo.AuthenticationType == AuthenticationType.Public) { Thread.CurrentPrincipal = GlobalConstants.GenericPrincipal; } var userPrinciple = Thread.CurrentPrincipal; Common.Utilities.PerformActionInsideImpersonatedContext(userPrinciple, () => { result = ExecuteWf(to, serviceTestModelTo); }); if (DataObject.Environment.Errors != null) { foreach (var err in DataObject.Environment.Errors) { errors.AddError(err, true); } } if (DataObject.Environment.AllErrors != null) { foreach (var err in DataObject.Environment.AllErrors) { errors.AddError(err, true); } } Dev2Logger.Info($"Completed Execution for Service Name:{DataObject.ServiceName} Resource Id: {DataObject.ResourceID} Mode:{(DataObject.IsDebug ? "Debug" : "Execute")}"); return(result); }
// Dont link this list public static void Create(BotClass bot) { var imp = new Impersonator(); try { if (bot.UseWindowsUser) { imp.Impersonate(bot.WindowsUserName, "localhost", bot.WindowsUserPassword); } bot.Status = "Create Diablo Clone"; string basepath = Path.GetDirectoryName(bot.Diablo.Location); string clonepath = Path.Combine(bot.DiabloCloneLocation, "Diablo III"); // if diablo base path does not exist stop here! if (basepath != null && !Directory.Exists(basepath)) { bot.Stop(); throw new Exception("Diablo base directory does not exist!"); } // Check if given language is installed on basepath string testpath = Path.Combine(basepath, @"Data_D3\PC\MPQs", General.GetLocale(bot.Diablo.Language)); if (!Directory.Exists(testpath)) { bot.Stop(); throw new Exception(string.Format("ERROR: {0} language is not installed (path: {1})", bot.Diablo.Language, testpath)); } // if diablo clone does not exist create it if (!Directory.Exists(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache"))) { Logger.Instance.Write(bot, "Creating new Diablo Clone"); Directory.CreateDirectory(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache")); } // Create Search caches var baseFileCache = new FileListCache(basepath); var cloneFileCache = new FileListCache(clonepath); // Check if all links are made for our clone foreach (FileListCache.MyFile p in baseFileCache.FileList) { try { if (p.directory && !Directory.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower()))) { if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path))) { Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path)); //if (!CreateSymbolicLink( Path.Combine(clonepath,p.Path), Path.Combine(basepath,p.Path), 1)) // throw new Exception("Failed to create link!"); Directory.CreateDirectory(Path.Combine(clonepath, p.Path)); } continue; } if (!p.directory && !File.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower()))) { if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path))) { Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path)); if (Path.GetExtension(Path.Combine(clonepath, p.Path)).ToLower().Equals(".exe")) { if ( !CreateHardLink(Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path), IntPtr.Zero)) { throw new Exception("Failed to create link!"); } } else { if ( !CreateSymbolicLink(Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path), 0)) { throw new Exception("Failed to create link!"); } } } } } catch (Exception ex) { Console.WriteLine(ex); } } // Remove links that have no target /* * foreach (var p in cloneFileCache.FileList) * { * try * { * if (p.directory && !Directory.Exists(Path.Combine(basepath, p.Path))) * { * if (!_noLinks.Any(n => General.WildcardMatch(n.Source.ToLower(), p.Path.ToLower()))) * Console.WriteLine("Delete: {0}", p.Path); * continue; * } * * if (!p.directory && !File.Exists(Path.Combine(basepath.ToLower(), p.Path.ToLower()))) * { * if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path))) * Console.WriteLine("Delete: {0}", p.Path); * } * } * catch (Exception ex) * { * Logger.Instance.Write(bot, ex.ToString()); * } * } */ } catch (Exception ex) { bot.Stop(); DebugHelper.Write(bot, "Failed to create clone!"); DebugHelper.Exception(ex); } imp.Dispose(); }
static void Main(string[] args) { Impersonator i = null; try { // Change theses to a user on your domain string SampleUsername = "******"; string SamplePassword = "******"; string SampleDomain = ""; // Say Current User Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); #region Impersonating a User i = new Impersonator(SampleUsername, SampleDomain, SamplePassword); i.Impersonate(); // ... Run Code // ... // Say Current User Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); i.Undo(); #endregion // Say Current User Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); #region Impersonating a User with the using cluase using (Impersonator im = new Impersonator(SampleUsername, SampleDomain, SamplePassword)) { im.Impersonate(); // ... Run Code // ... // Say Current User Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); } #endregion Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); #region Impersonating a User with a Timer i = new Impersonator(SampleUsername, SampleDomain, SamplePassword, 100); i.Impersonate(); // ... Run Code System.Threading.Thread.Sleep(1000); // Say Current User Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); //TODO: Fix duplicat emessage in event log // i.Undo(); // NOTE: Note needed with a timer! but can be called. #endregion } catch (LogonException le) { Console.WriteLine(le.ToString()); } finally { // Say Current User Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name); Console.ReadLine(); } }