private void GetAllQueues(object sender, System.ComponentModel.DoWorkEventArgs e) { object[] par = e.Argument as object[]; string _mashineName = par[0] as string; bool useCurUser = (bool)par[1]; List <string> result = new List <string>(); if (useCurUser) { MessageQueue[] QueueList = MessageQueue.GetPrivateQueuesByMachine(_mashineName); foreach (MessageQueue q in QueueList) { result.Add(q.QueueName); } result.Sort(); } else { string username = "******"; string domain = "avant"; using (Impersonator imp = new Impersonator(username, domain, "Daw18!otM")) { MessageQueue[] QueueList = MessageQueue.GetPrivateQueuesByMachine(_mashineName); foreach (MessageQueue q in QueueList) { result.Add(q.QueueName); } result.Sort(); } } e.Result = result; }
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"); } }
// ReSharper disable InconsistentNaming public void SqlDatabaseBroker_TestService_WindowsUserWithDbAccess_ReturnsValidResult() // ReSharper restore InconsistentNaming { Impersonator.RunAs("IntegrationTester", "DEV2", "I73573r0", () => { var dbSource = SqlServerTests.CreateDev2TestingDbSource(AuthenticationType.Windows); var serviceConn = new DbService { ResourceID = Guid.NewGuid(), ResourceName = "DatabaseService", ResourceType = ResourceType.DbService, ResourcePath = "Test", AuthorRoles = "", Dependencies = new List <IResourceForTree>(), FilePath = null, IsUpgraded = true, Method = new ServiceMethod("dbo.fn_diagramobjects", "\r\n\tCREATE FUNCTION dbo.fn_diagramobjects() \r\n\tRETURNS int\r\n\tWITH EXECUTE AS N'dbo'\r\n\tAS\r\n\tBEGIN\r\n\t\tdeclare @id_upgraddiagrams\t\tint\r\n\t\tdeclare @id_sysdiagrams\t\t\tint\r\n\t\tdeclare @id_helpdiagrams\t\tint\r\n\t\tdeclare @id_helpdiagramdefinition\tint\r\n\t\tdeclare @id_creatediagram\tint\r\n\t\tdeclare @id_renamediagram\tint\r\n\t\tdeclare @id_alterdiagram \tint \r\n\t\tdeclare @id_dropdiagram\t\tint\r\n\t\tdeclare @InstalledObjects\tint\r\n\r\n\t\tselect @InstalledObjects = 0\r\n\r\n\t\tselect \t@id_upgraddiagrams = object_id(N'dbo.sp_upgraddiagrams'),\r\n\t\t\t@id_sysdiagrams = object_id(N'dbo.sysdiagrams'),\r\n\t\t\t@id_helpdiagrams = object_id(N'dbo.sp_helpdiagrams'),\r\n\t\t\t@id_helpdiagramdefinition = object_id(N'dbo.sp_helpdiagramdefinition'),\r\n\t\t\t@id_creatediagram = object_id(N'dbo.sp_creatediagram'),\r\n\t\t\t@id_renamediagram = object_id(N'dbo.sp_renamediagram'),\r\n\t\t\t@id_alterdiagram = object_id(N'dbo.sp_alterdiagram'), \r\n\t\t\t@id_dropdiagram = object_id(N'dbo.sp_dropdiagram')\r\n\r\n\t\tif @id_upgraddiagrams is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 1\r\n\t\tif @id_sysdiagrams is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 2\r\n\t\tif @id_helpdiagrams is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 4\r\n\t\tif @id_helpdiagramdefinition is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 8\r\n\t\tif @id_creatediagram is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 16\r\n\t\tif @id_renamediagram is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 32\r\n\t\tif @id_alterdiagram is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 64\r\n\t\tif @id_dropdiagram is not null\r\n\t\t\tselect @InstalledObjects = @InstalledObjects + 128\r\n\t\t\r\n\t\treturn @InstalledObjects \r\n\tEND\r\n\t", null, null, null, "dbo.fn_diagramobjects"), Recordset = new Recordset(), Source = dbSource }; var broker = new SqlDatabaseBroker(); var result = broker.TestService(serviceConn); Assert.AreEqual(OutputFormats.ShapedXML, result.Format); }); }
private void excuteJobExportTdw() { //long result; var imp = new Impersonator(); imp.ImpersonateAndExecute("cdtasvc-ECP_User_Dev", "Srp4acct!", "INTERNAL", () => { ExecutePackage(); }); }
public void Usage() { Impersonator.RunImpersonatedAction("domain.local", "username", "password", () => { //Do something here with account [email protected] }); }
/// <summary> /// Does the sequence. /// </summary> /// <param name="isAContinueRun">Whether this run is a continue run.</param> /// <returns>True if success else false.</returns> public bool DoSequence(bool isAContinueRun = false) { try { Impersonator impersonator = new Impersonator( Properties.Settings.Default.CommandsUserName, Properties.Settings.Default.CommandsDomain, Properties.Settings.Default.CommandsPassword ); // 1. List the databases that would be impacted // Already listed in the contruction function // 2. Backup the databases if exist, else created a new one BackupDatabasesAndDisableConstraints(isAContinueRun); // 3. Import data into the databases listed ImportDataIntoDatabasesListed(isAContinueRun); // 4) Enalbe all constraints on all tables in the database EnableConstraints(); EnableIndexes(); return(this.exceptions == null || this.exceptions.Count <= 0); } catch (Exception ex) { ExceptionHelper.CentralProcess(ex); return(false); } }
public void Imperson_Upload_Success_Test() { using (var copy = new Impersonator()) { Assert.True(copy.Impersonate(uncDomain, uncUser, uncPassword)); copy.Upload(uncPath, @"D:", @"test.txt"); } }
public static bool UseImpersonation(IIdentity user) { bool rc = true; if (SynapseServer.Config.WebApi.UseImpersonation == false) { rc = false; } else if (SynapseServer.Config.WebApi.Authentication.Scheme == System.Net.AuthenticationSchemes.Anonymous) { rc = false; } else { string currentUser = user?.Name; string runningAsUser = Impersonator.WhoAmI()?.Name; if (currentUser == null) { rc = false; } else if (currentUser.ToLower() == runningAsUser.ToLower()) { rc = false; } } return(rc); }
public void Intercept(IInvocation invocation) { using (var I = new Impersonator("user", ".", "password")) { invocation.Proceed(); } }
private static string GetJson(string structRootPath) { Impersonator imp = null; if (StorageUtility.NeedImpersonation(structRootPath)) { imp = StorageUtility.GetImpersonator(); } try { var structXml = Path.Combine(structRootPath, @"Metadata\Structure.xml"); var structure = MetadataStructure.GetFromFile(structXml); //var dir = Path.GetDirectoryName(structXml); //var jsonFile = Path.Combine(dir, "metadataAlias.json"); //structure.ToFile(jsonFile, false, true); var jsonFile = JsonConvert.SerializeObject(structure.GetAliases(), Formatting.None); return(jsonFile); } finally { if (imp != null) { imp.Dispose(); } } }
public void TestThatUserNameWithNoDomainFormatsCorrectly() { var username = "******"; Assert.That(Impersonator.GetUserName(username), Is.EqualTo(username)); Assert.That(Impersonator.GetDomain(username), Is.EqualTo("")); }
public void modesConnect() { int index = 0; while (!ModesApiFactory.IsInitilized && index <= 10) { try { using (Impersonator imp = new Impersonator(MCSettings.Single.MCUser, "corp", MCSettings.Single.MCPassword)) { Logger.Info(String.Format("Подключение к MC. Попытка {0}", index)); //ModesApiFactory.Initialize(MCSettings.Single.MCServer, MCSettings.Single.MCUser, MCSettings.Single.MCPassword); ModesApiFactory.Initialize(MCSettings.Single.MCServer); api = ModesApiFactory.GetModesApi(); } /*Logger.Info(String.Format("Подключение к MC. Попытка {0}", index)); * ModesApiFactory.Initialize(MCSettings.Single.MCServer, "mc_votges", "mcV0tges"); * api = ModesApiFactory.GetModesApi();*/ } catch (Exception e) { Logger.Info(e.ToString()); } index++; } }
/// <summary> /// Execute this step. /// </summary> protected override void ExecuteMain() { StringBuilder sb = new StringBuilder(); try { this.Status = StepStatusEnum.Executing; bool success = true; Impersonator impersonator = new Impersonator( Properties.Settings.Default.DomainUserName, Properties.Settings.Default.Domain, Properties.Settings.Default.DomainPassword ); DataImporter importer = new DataImporter(); success = importer.DoSequence(Properties.Settings.Default.DataImporter_IsContinueRun); if (success) { if (importer.Exceptions == null || importer.Exceptions.Count <= 0) { if (importer.TargetDataFileInfoList.Count > 0) { this.Status = StepStatusEnum.Pass; this.ResultDetail = new StepResultDetail("Successfully imported data into databases. Total data file(s) processed: {0}".FormatWith(importer.TargetDataFileInfoList.Count)); } else { this.Status = StepStatusEnum.Warning; this.ResultDetail = new StepResultDetail("This step didn't meet any error, however, no data file has been found under the specified path '{0}' or '{1}'.".FormatWith(Microsoft.Scs.Test.RiskTools.RulePerf.Properties.Settings.Default.BedTransferFolder, Properties.Settings.Default.DataImporter_DataDirectory)); } } else { this.Status = StepStatusEnum.Failed; this.ResultDetail = new StepResultDetail("Met errors during importing. Total data file(s) processed: {0}".FormatWith(importer.TargetDataFileInfoList.Count), importer.Exceptions); } } else { this.Status = StepStatusEnum.Failed; this.ResultDetail = new StepResultDetail("Importing data failed. Please check logs for more detailed information."); } } catch (Exception ex) { this.Status = StepStatusEnum.Failed; this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex)); } finally { if (this.ResultDetail != null) { string message = sb.ToString(); if (!string.IsNullOrEmpty(message)) { this.ResultDetail.Message += "Execution log: \r\n{0}".FormatWith(message); } } } }
public virtual object query(SqlDataAdapter adapter, AbstractPermission permission = null) { Impersonator imp = null; try { if (_impersonationUser != null) { imp = new Impersonator(_impersonationUser); } using (SqlConnection newCxn = new SqlConnection(this.DataSource.ConnectionString)) { newCxn.Open(); if (adapter.SelectCommand != null) { adapter.SelectCommand.Connection = newCxn; //DataSet results = new DataSet(); //adapter.Fill(results); //return results; SqlDataReader rdr = adapter.SelectCommand.ExecuteReader(); // the SqlDataReader will be closed at the exit of this using block so we copy everything over to our MockDataReader where it will be cached in a DataTable MockDataReader mock = new MockDataReader(); DataTable newTable = new DataTable(); newTable.Load(rdr); mock.Table = newTable; // the previous couple lines are broken out so the setter on MockDataReader.Table can properly map the column names - IMPORTANT!! return(mock); } else if (adapter.DeleteCommand != null) { adapter.DeleteCommand.Connection = newCxn; return(adapter.DeleteCommand.ExecuteNonQuery()); } else if (adapter.UpdateCommand != null) { adapter.UpdateCommand.Connection = newCxn; return(adapter.UpdateCommand.ExecuteNonQuery()); } else if (adapter.InsertCommand != null) { adapter.InsertCommand.Connection = newCxn; return(adapter.InsertCommand.ExecuteNonQuery()); } throw new ArgumentException("Must supply a SQL command"); } } catch (Exception) { throw; } finally { if (imp != null) { imp.stopImpersonation(); } } }
static KeyValuePair <String, String> getRangeFromCdw(String sitecode) { String sql = "SELECT MIN(CAST(BCMAMedicationLogIEN AS INTEGER))-1 FROM BCMA.BCMAMedicationLog WHERE Sta3n=" + sitecode + " AND EnteredVistaDate LIKE('3100101%') UNION " + "SELECT MAX(CAST(BCMAMedicationLogIEN AS INTEGER)) FROM BCMA.BCMAMedicationLog WHERE Sta3n=" + sitecode; //String sql = "SELECT MAX(CAST(BCMAMedicationLogIEN AS INTEGER)) FROM BCMA.BCMAMedicationLog WHERE Sta3n=" + sitecode; gov.va.medora.mdo.User impersonationUser = new User() { UserName = ConfigurationManager.AppSettings["CdwUserName"], Pwd = ConfigurationManager.AppSettings["CdwUserPassword"], Domain = ConfigurationManager.AppSettings["CdwUserDomain"] }; String connectionString = "Data Source=127.0.0.1;Initial Catalog=CDWWork;Trusted_Connection=true"; using (gov.va.medora.mdo.dao.ldap.Impersonator imp = new Impersonator(impersonationUser)) { using (System.Data.SqlClient.SqlConnection newCxn = new System.Data.SqlClient.SqlConnection(connectionString)) { newCxn.Open(); System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); cmd.Connection = newCxn; cmd.CommandText = sql; cmd.CommandTimeout = 60 * 60 * 10; IDataReader rdr = cmd.ExecuteReader(); rdr.Read(); String startIen = Convert.ToString(rdr.GetInt32(0)); rdr.Read(); String stopIen = Convert.ToString(rdr.GetInt32(0)); return(new KeyValuePair <string, string>(startIen, stopIen)); // Convert.ToString((Int32)cmd.ExecuteScalar()); } } }
/// <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 async Task <ActionResult> Descarga(BusquedaExpedienteViewModel datosDescarga) { IExportadorDocumentos <DocumentoRepositorio> exportadorRepositorio = null; IOperacionesRepositorio <DocumentoRepositorio> operacionesRepositorio = null; if (datosDescarga.ArchivosExpediente != null && datosDescarga.ArchivosExpediente.Count > 0) { //1. Nos conectamos al repositorio y bajamos los documentos especificados //Impersonado para Laserfiche using (Impersonator impersonator = new Impersonator("dah.programador01", "AD-HINOJOSA", "Hinojosa2018")) { using (Laserfiche.RepositoryAccess.Session sesion = Laserfiche.RepositoryAccess.Session.Create("SERVERWA", "DA-HINOJOSA")) { exportadorRepositorio = RepositorioDocumentosFactory.CrearExportador(Repositorio.Laserfiche, sesion); operacionesRepositorio = RepositorioDocumentosFactory.CrearOperaciones(Repositorio.Laserfiche, sesion); DocumentoRepositorio[] listaDocumentos = datosDescarga.ArchivosExpediente.Where(w => w.Seleccionado).Select(s => operacionesRepositorio.ObtenerArchivoPorId(s.Identificador)).ToArray(); Guid temporalGuid = Guid.NewGuid(); string rutaTemporal = Server.MapPath("~/" + ConfigurationManager.AppSettings["RutaTemporalDescargas"] + temporalGuid.ToString()); Directory.CreateDirectory(rutaTemporal); await exportadorRepositorio.ExportarAsync(listaDocumentos, rutaTemporal, true); //Borrar los archivos temporales después de descargar var fileInfo = new FileInfo($"{rutaTemporal}.zip"); long byteSize = fileInfo.Length; byte[] fileByteArray = new byte[byteSize]; fileByteArray = System.IO.File.ReadAllBytes($"{rutaTemporal}.zip"); System.IO.File.Delete($"{rutaTemporal}.zip"); System.IO.Directory.Delete($"{rutaTemporal}", true); //Se obtienen datos de pedimento PedimentosSaaiSirView pedimento = null; if (!string.IsNullOrEmpty(datosDescarga.Referencia)) { pedimento = _catalogos.PedimentosSaaiSirViews.FirstOrDefault(f => f.Referencia == datosDescarga.Referencia); pedimento = pedimento ?? await BuscarPedimentoSAAI(datosDescarga, pedimento); if (pedimento != null) { datosDescarga.Aduana = datosDescarga.Aduana ?? pedimento.Aduana; datosDescarga.Año = datosDescarga.Año ?? pedimento.FechaPago.Value.Year.ToString(); datosDescarga.Pedimento = datosDescarga.Pedimento ?? pedimento.Pedimento; datosDescarga.Referencia = datosDescarga.Referencia ?? pedimento.Referencia; } } return(File(fileByteArray, "application/zip", $"{datosDescarga.Año.Substring(2,2)} {datosDescarga.Aduana} {datosDescarga.Pedimento}.zip")); } } } return(HttpNotFound()); }
private async Task <UserInfo> AuthenticateUserAsync(string userName, string password) { // Find in catalog (not found error) var ui = await _userManager.GetUserInfoAsync(userName); if (ui == null) { throw new AuthenticationException($"Login for name '{userName}' not registered in system catalog"); } string impersonateType = ui.Identity.AuthenticationType; if (impersonateType.Equals("windows", StringComparison.OrdinalIgnoreCase)) { try { Impersonator.Execute <bool>(userName, password, () => true); } catch (Exception ex) { throw new AuthenticationException($"Authentication failed for user '{userName}'", ex); } } else //basic { if (!ui.PasswordHash.Equals(CryptoHelper.ComputeSha256Hash(password), StringComparison.Ordinal)) { throw new AuthenticationException($"Bad password for user '{userName}'"); } } return(ui); }
public long StartPlan(string planUniqueName, bool dryRun = false, string requestNumber = null, string nodeRootUrl = null) { InitPlanServer(); if (!string.IsNullOrWhiteSpace(requestNumber)) { requestNumber = System.Web.HttpUtility.UrlDecode(requestNumber); } if (!string.IsNullOrWhiteSpace(nodeRootUrl)) { requestNumber = System.Web.HttpUtility.UrlDecode(nodeRootUrl); } Uri uri = CurrentUrl.Request.RequestUri; string context = GetContext(nameof(StartPlan), nameof(CurrentUserName), CurrentUserName, nameof(planUniqueName), planUniqueName, nameof(dryRun), dryRun, nameof(requestNumber), requestNumber, nameof(nodeRootUrl), nodeRootUrl, "QueryString", uri.Query); Impersonator runAsUser = null; if (SynapseServer.UseImpersonation(CurrentUser?.Identity)) { if (Request?.Headers?.Authorization?.Scheme?.ToLower() == "basic") { runAsUser = new Impersonator(this.AuthenticationHeader); } else { runAsUser = new Impersonator((WindowsIdentity)(CurrentUser?.Identity)); } runAsUser.Start(SynapseServer.Logger); } try { SynapseServer.Logger.Debug(context); Dictionary <string, string> dynamicParameters = uri.ParseQueryString(); if (dynamicParameters.ContainsKey(nameof(dryRun))) { dynamicParameters.Remove(nameof(dryRun)); } return(_server.StartPlan(CurrentUserName, planUniqueName, dryRun, requestNumber, dynamicParameters, nodeRootUrl: nodeRootUrl, referrer: CurrentUrl.Request.RequestUri, authHeader: this.AuthenticationHeader)); } catch (Exception ex) { SynapseServer.Logger.Error( Utilities.UnwindException(context, ex, asSingleLine: true)); throw; } finally { runAsUser?.Stop(SynapseServer.Logger); } }
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); } }
// ReSharper disable InconsistentNaming public void SqlDatabaseBroker_GetServiceMethods_WindowsUserWithDbAccess_GetsMethods() // ReSharper restore InconsistentNaming { Impersonator.RunAs("IntegrationTester", "DEV2", "I73573r0", () => { var dbSource = SqlServerTests.CreateDev2TestingDbSource(AuthenticationType.Windows); var broker = new SqlDatabaseBroker(); var result = broker.GetServiceMethods(dbSource); Assert.AreEqual(true, result.Count > 0); }); }
public static void RunStemming() { using (var imp = new Impersonator("pavel", "LANGMaster", "zvahov88_")) RunStemming <List <string> >( crsLangs, lng => LingeaDictionary.wordsForCourse(XmlUtils.FileToObject <schools.DictCrsWords>(string.Format(@"d:\LMCom\rew\Web4\RwDicts\UsedWords\CourseWords_{0}.xml", lng))).Select(w => w.word.ToLower().Trim()).Distinct().ToArray(), lng => new List <string>(), (lng, word, row, res) => res.Add(row.AgregateSB((sb, i) => { sb.Append("|"); sb.Append(i); })), (lng, res) => File.WriteAllLines(string.Format(@"d:\LMCom\rew\Web4\RwDicts\UsedWords\CourseWordsStems_{0}.txt", lng), res), imp ); }
protected override void ExecuteMain() { try { StringBuilder sb = new StringBuilder(); this.Status = StepStatusEnum.Executing; Impersonator impersonator = new Impersonator( Properties.Settings.Default.DomainUserName, Properties.Settings.Default.Domain, Properties.Settings.Default.DomainPassword); foreach (string ruleId in Properties.Settings.Default.RuleIds) { string sourcePath = Path.Combine( Properties.Settings.Default.RuleSourceFolder, "{0}.dat.gz".FormatWith(ruleId) ); string destFolder = Properties.Settings.Default.RuleDestFolder; if (!destFolder.EndsWith("\\")) { destFolder += "\\"; } string destPath = Path.Combine( Path.GetDirectoryName(destFolder), "{0}.dat.gz".FormatWith(ruleId) ); File.Copy(sourcePath, destPath, true); sb.AppendLine("Copied {0} to {1}".FormatWith(sourcePath, destPath)); // Decompress is not needed any more after Harry's update to MixMerge.exe tool //AsyncDecompress(destPath); //Decompress(destPath); } impersonator.Undo(); this.Status = StepStatusEnum.Pass; this.ResultDetail = new StepResultDetail(sb.ToString() + "\r\nSuccessfully prepared the gz files."); } catch (Exception ex) { this.Status = StepStatusEnum.Failed; this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex)); } finally { if (this.ResultDetail != null) { Log.Info(this.ResultDetail.Message); } } }
private async Task <IJobResult> DoRunAsync() { bool shouldImpersonate = !request.Privileged; var commandFactory = new TaskCommandFactory(container, shouldImpersonate, request.Rlimits); var credential = container.GetCredential(); var results = new List <TaskCommandResult>(); foreach (TaskCommandDTO cmd in commands) { if (cts.IsCancellationRequested) { break; } TaskCommand taskCommand = commandFactory.Create(cmd.Command, cmd.Args); try { var processCommand = taskCommand as ProcessCommand; if (runningAsync && processCommand != null) { // NB: ProcessCommands take care of their own impersonation processCommand.StatusAvailable += processCommand_StatusAvailable; try { TaskCommandResult result = await processCommand.ExecuteAsync(); results.Add(result); } finally { processCommand.StatusAvailable -= processCommand_StatusAvailable; } } else { using (Impersonator.GetContext(credential, shouldImpersonate)) { results.Add(taskCommand.Execute()); } } } catch (Exception ex) { results.Add(new TaskCommandResult(1, null, ex.Message)); break; } } return(FlattenResults(results)); }
public void StartPlanAsync(long planInstanceId, bool dryRun, [FromBody] string planString) { Uri uri = this.Url.Request.RequestUri; planString = CryptoHelpers.Decode(planString); Plan plan = Plan.FromYaml(new StringReader(planString)); string context = GetContext(nameof(StartPlanAsync), nameof(plan), plan.Name, nameof(dryRun), dryRun, nameof(planInstanceId), planInstanceId, "QueryString", uri.Query); Impersonator runAsUser = null; if (SynapseServer.UseImpersonation(User?.Identity)) { if (Request?.Headers?.Authorization?.Scheme?.ToLower() == "basic") { runAsUser = new Impersonator(Request.Headers.Authorization); } else { runAsUser = new Impersonator((WindowsIdentity)User.Identity); } runAsUser.Start(SynapseServer.Logger); } try { SynapseServer.Logger.Debug(context); plan.InstanceId = planInstanceId; ValidatePlanSignature(plan); Dictionary <string, string> dynamicParameters = uri.ParseQueryString(); if (dynamicParameters.ContainsKey(nameof(dryRun))) { dynamicParameters.Remove(nameof(dryRun)); } PlanRuntimePod p = new PlanRuntimePod(plan, dryRun, dynamicParameters, plan.InstanceId, this.Url.Request.Headers.Referrer, this.Request?.Headers?.Authorization); _scheduler.StartPlan(p); } catch (Exception ex) { SynapseServer.Logger.Error( Utilities.UnwindException(context, ex, asSingleLine: true)); throw; } finally { runAsUser?.Stop(SynapseServer.Logger); } }
public DateTime GetLastWriteTime(string filepath, Impersonator authorizingUser = null) { { if (Directory.Exists(filepath)) { Directory.GetLastWriteTime(filepath); } else if (File.Exists(filepath)) { return(File.GetLastWriteTime(filepath)); } return(DateTime.MinValue); } }
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); }
public void Impersonate() { try { using (var context = new Impersonator("imstestu12", "rta", "Password12")) { var calc = Process.Start(@"C:\Windows\System32\calc.exe"); Thread.Sleep(2000); calc.Kill(); } } catch (Win32Exception ex) { Console.WriteLine(ex.Message); } }
protected virtual void PostExecute() { string logPath = Properties.Settings.Default.ResultLogPath.Trim(); if (!string.IsNullOrEmpty(logPath)) { ////FileAttributes attr = File.GetAttributes(logPath); ////if ((attr & FileAttributes.Directory) != FileAttributes.Directory) if (IsFilePath(logPath)) { // Only serialize when the logPath is a filename (not a directory name) Impersonator impersonateor = new Impersonator( Properties.Settings.Default.DomainUserName, Properties.Settings.Default.Domain, Properties.Settings.Default.DomainPassword); try { // There was an error reflecting type 'RulePerf.Model.RestartMachinesStep'. //XmlSerializer xmlSerializer = new XmlSerializer(this.GetType()); //using (XmlWriter writer = XmlWriter.Create(logPath)) //{ // xmlSerializer.Serialize(writer, this); //} BinaryFormatter bf = new BinaryFormatter(); using (Stream output = File.OpenWrite(logPath)) { bf.Serialize(output, this); output.Flush(); output.Close(); } } catch (Exception ex) { ExceptionHelper.CentralProcess(ex); } finally { try { impersonateor.Undo(); } finally { } } } } }
protected override void ExecuteMain() { try { this.Status = StepStatusEnum.Executing; Impersonator impersonator = new Impersonator( Properties.Settings.Default.CommandsUserName, Properties.Settings.Default.CommandsDomain, Properties.Settings.Default.CommandsPassword ); System.Collections.Generic.List <CommandExecutionResult> results = new CmdHelper().ExecuteCommandsConcurrently( Properties.Settings.Default.Commands.ToArray(), Properties.Settings.Default.CommandsUserName, Properties.Settings.Default.CommandsPassword, Properties.Settings.Default.CommandsDomain); this.Status = StepStatusEnum.Pass; this.ResultDetail = new StepResultDetail(""); StringBuilder sb = new StringBuilder(); this.ResultDetail.Exceptions = new List <Exception>(); foreach (CommandExecutionResult result in results) { if (result.ExitCode != 0) { this.Status = StepStatusEnum.Failed; } sb.Append(result.StandardOutput.ToString()); this.ResultDetail.Exceptions.Add(new Exception(result.StandardError.ToString())); } this.ResultDetail.Message = sb.ToString(); } catch (Exception ex) { this.Status = StepStatusEnum.Failed; this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex)); } finally { if (this.ResultDetail != null) { Log.Info(this.ResultDetail.Message); } } }
public IJobResult Run() { bool shouldImpersonate = !request.Privileged; var commandFactory = new TaskCommandFactory(container, shouldImpersonate, request.Rlimits); var credential = container.GetCredential(); var results = new List <TaskCommandResult>(); foreach (TaskCommandDTO cmd in commands) { if (cts.IsCancellationRequested) { break; } TaskCommand taskCommand = commandFactory.Create(cmd.Command, cmd.Args); try { TaskCommandResult result = null; if (taskCommand is ProcessCommand) { // NB: ProcessCommands take care of their own impersonation result = taskCommand.Execute(); } else { using (Impersonator.GetContext(credential, shouldImpersonate)) { result = taskCommand.Execute(); } } results.Add(result); } catch (Exception ex) { log.TraceException("Error running command", ex); results.Add(new TaskCommandResult(1, null, ex.Message)); break; } } return(FlattenResults(results)); }
/// <summary> /// Runs the specified service using the command console as a user interface. /// </summary> /// <param name="service">The service.</param> /// <param name="runMode">The run mode.</param> /// <param name="defaultLogFormat">The default log format.</param> /// <param name="defaultLoggingLevels">The default logging levels.</param> /// <param name="token">The token.</param> /// <returns> /// An awaitable task. /// </returns> // ReSharper disable once CodeAnnotationAnalyzer public static async Task RunAsync( [NotNull] BaseService service, RunMode runMode = RunMode.Default, [CanBeNull] FormatBuilder defaultLogFormat = null, LoggingLevels defaultLoggingLevels = LoggingLevels.All, CancellationToken token = default(CancellationToken)) { if (service == null) throw new ArgumentNullException("service"); if (!ConsoleHelper.IsConsole) return; Console.Clear(); Log.SetTrace(validLevels: LoggingLevels.None); Log.SetConsole(defaultLogFormat ?? Log.ShortFormat, defaultLoggingLevels); await Log.Flush(token).ConfigureAwait(false); Impersonator impersonator = null; try { if (runMode.HasFlag(RunMode.Prompt)) { Debug.Assert(service.ServiceName != null); // Whether we start will depend on the selected option in prompt. runMode = runMode.Clear(RunMode.Start, true); Console.Title = ServiceResources.ConsoleConnection_RunAsync_ConfigureTitle + service.ServiceName; bool done = false; do { if (token.IsCancellationRequested) return; Dictionary<string, string> options = new Dictionary<string, string> { { "I", ServiceResources.ConsoleConnection_RunAsync_OptionInstall }, { "U", ServiceResources.ConsoleConnection_RunAsync_OptionUninstall }, { "S", ServiceResources.ConsoleConnection_RunAsync_OptionStart }, { "R", ServiceResources.ConsoleConnection_RunAsync_OptionRestart }, { "T", ServiceResources.ConsoleConnection_RunAsync_OptionStop }, { "P", ServiceResources.ConsoleConnection_RunAsync_OptionPause }, { "C", ServiceResources.ConsoleConnection_RunAsync_OptionContinue }, { "Y", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmd }, { "V", ServiceResources.ConsoleConnection_RunAsync_OptionStartCmd }, { "W", ServiceResources.ConsoleConnection_RunAsync_OptionRunCmdNewCredentials }, { "Z", ServiceResources.ConsoleConnection_RunAsync_OptionRunNoInteraction }, { "X", ServiceResources.ConsoleConnection_RunAsync_OptionExit } }; if (!runMode.HasFlag(RunMode.Interactive)) { options.Remove("V"); options.Remove("Y"); options.Remove("W"); } bool isAdmin; string currentUser; try { WindowsIdentity identity = WindowsIdentity.GetCurrent(); currentUser = identity.Name; Debug.Assert(identity != null); WindowsPrincipal principal = new WindowsPrincipal(identity); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } catch { isAdmin = false; currentUser = null; } if (!string.IsNullOrEmpty(currentUser)) { FormatBuilder fb = new FormatBuilder() .AppendForegroundColor(ConsoleColor.Cyan) .Append("Current User: "******" [Admin]"); fb.AppendLine().WriteToConsole(); } if (!isAdmin) { options.Remove("I"); options.Remove("U"); } if (Controller.ServiceIsInstalled(service.ServiceName)) { ServiceControllerStatus state = Controller.GetServiceStatus(service.ServiceName); new FormatBuilder() .AppendForegroundColor(ConsoleColor.White) .AppendFormatLine( ServiceResources.ConsoleConnection_RunAsync_ServiceInstalledState, service.ServiceName, state) .AppendResetForegroundColor() .WriteToConsole(); options.Remove("I"); switch (state) { case ServiceControllerStatus.StopPending: case ServiceControllerStatus.Stopped: // Service is stopped or stopping. options.Remove("C"); options.Remove("R"); options.Remove("T"); break; case ServiceControllerStatus.StartPending: case ServiceControllerStatus.ContinuePending: case ServiceControllerStatus.Running: // Service is starting or running. options.Remove("S"); options.Remove("C"); break; case ServiceControllerStatus.PausePending: case ServiceControllerStatus.Paused: // Service is paused or pausing. options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("P"); break; default: // Service is not installed - shouldn't happen. options.Remove("U"); options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("C"); options.Remove("P"); break; } options.Remove("V"); options.Remove("Y"); options.Remove("Z"); } else { // No service installed. options.Remove("U"); options.Remove("S"); options.Remove("R"); options.Remove("T"); options.Remove("P"); options.Remove("C"); } _promptInstall.WriteToConsole( null, // ReSharper disable once PossibleNullReferenceException (_, c) => !string.Equals(c.Tag, "options", StringComparison.CurrentCultureIgnoreCase) ? Resolution.Unknown : options); string key; do { key = Char.ToUpperInvariant(Console.ReadKey(true).KeyChar) .ToString(CultureInfo.InvariantCulture); } while (!options.ContainsKey(key)); try { string userName; string password; switch (key) { case "I": GetUserNamePassword(out userName, out password); service.Install(ConsoleTextWriter.Default, userName, password); Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitInstall); while (!Controller.ServiceIsInstalled(service.ServiceName)) { await Task.Delay(250, token).ConfigureAwait(false); Console.Write('.'); } Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "U": await service.Uninstall(ConsoleTextWriter.Default, token).ConfigureAwait(false); Console.Write(ServiceResources.ConsoleConnection_RunAsync_WaitUninstall); while (Controller.ServiceIsInstalled(service.ServiceName)) { await Task.Delay(250, token).ConfigureAwait(false); Console.Write('.'); } Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "R": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop); await Controller.StopService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart); await Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "S": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStart); await Controller.StartService(service.ServiceName, null, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "T": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingStop); await Controller.StopService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "P": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingPause); await Controller.PauseService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); break; case "C": Console.Write(ServiceResources.ConsoleConnection_RunAsync_AttemptingContinue); await Controller.ContinueService(service.ServiceName, token).ConfigureAwait(false); Console.WriteLine(ServiceResources.Done); Console.WriteLine(); break; case "V": runMode = runMode.Set(RunMode.Start, true).Set(RunMode.Interactive, true); done = true; break; case "Y": runMode = runMode.Set(RunMode.Interactive, true); done = true; break; case "W": GetUserNamePassword(out userName, out password); if (userName == null) break; Debug.Assert(password != null); Impersonator ei = impersonator; impersonator = null; if (ei != null) ei.Dispose(); // Run in new security context. impersonator = new Impersonator(userName, password); break; case "Z": runMode = runMode.Set(RunMode.Start, true).Clear(RunMode.Interactive, true); done = true; Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive); Console.WriteLine( ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive2); Console.WriteLine(); break; default: return; } } catch (TaskCanceledException) { return; } catch (Exception e) { if (!token.IsCancellationRequested) Log.Add(e); } } while (!done); } else if (!runMode.HasFlag(RunMode.Interactive)) // If we don't show prompt and we're not interactive we should always start the service. runMode = runMode.Set(RunMode.Start, true); // Create connection Console.Title = ServiceResources.ConsoleConnection_RunAsync_RunningTitle + service.ServiceName; ConsoleConnection connection = new ConsoleConnection(defaultLogFormat, defaultLoggingLevels, token); Guid id = service.Connect(connection); // Combined cancellation tokens. ITokenSource tSource = token.CreateLinked(connection._cancellationTokenSource.Token); try { CancellationToken t = tSource.Token; if (t.IsCancellationRequested) return; if (runMode.HasFlag(RunMode.Start)) { // Start the service await service.StartService(ConsoleTextWriter.Default, null, t).ConfigureAwait(false); if (t.IsCancellationRequested) return; } if (!runMode.HasFlag(RunMode.Interactive)) { // Wait to be cancelled as nothing to do. await t.WaitHandle; return; } do { // Flush logs await Log.Flush(t).ConfigureAwait(false); if (t.IsCancellationRequested) break; WritePrompt(service); try { string commandLine = await Console.In.ReadLineAsync().ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(commandLine)) { bool completed = false; ICancelableTokenSource commandCancellationSource = t.ToCancelable(); CancellationToken commandToken = commandCancellationSource.Token; #pragma warning disable 4014 service.ExecuteAsync(id, commandLine, ConsoleTextWriter.Default, commandToken) .ContinueWith( task => { Debug.Assert(task != null); completed = true; if (task.IsCompleted || task.IsCanceled) return; if (task.IsFaulted) { Debug.Assert(task.Exception != null); _errorFormat.WriteToConsoleInstance(null, task.Exception); } }, TaskContinuationOptions.ExecuteSynchronously); #pragma warning restore 4014 while (!completed) { if (!commandCancellationSource.IsCancellationRequested && Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { // Cancel command Console.Write(ServiceResources.ConsoleConnection_RunAsync_Cancelling); commandCancellationSource.Cancel(); break; } await Task.Delay(100, token).ConfigureAwait(false); } } } catch (TaskCanceledException) { throw; } catch (Exception e) { if (!t.IsCancellationRequested) _errorFormat.WriteToConsoleInstance(null, e); } // Let any async stuff done by the command have a bit of time, also throttle commands. await Task.Delay(500, t).ConfigureAwait(false); } while (!t.IsCancellationRequested); } catch (TaskCanceledException) { } finally { tSource.Dispose(); // ReSharper disable MethodSupportsCancellation Log.Flush().Wait(); // ReSharper restore MethodSupportsCancellation service.Disconnect(id); Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_PressKeyToExit); Console.ReadKey(true); } } finally { if (impersonator != null) impersonator.Dispose(); } }