public IEnumerable <VR_Rendimiento_A_Academ> GetYearsByUser(string userName) { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); this.db = new SGA_DesarrolloEntities(); var years = (from y in db.VR_Rendimiento_A_Academ join e in db.R_Estudiantes on y.Estudiante equals e.IdPersona join p in db.P_Personas on e.IdPersona equals p.IdPersona orderby y.A_Adem where p.login_red == userName select y ); return(years); } catch (System.Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public IEnumerable <VR_Rendimiento_Periodos> GetPeriodsByYearAndUser(string userName, int year) { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); this.db = new SGA_DesarrolloEntities(); var periods = (from p in db.VR_Rendimiento_Periodos join e in db.R_Estudiantes on p.Estudiante equals e.IdPersona join pe in db.P_Personas on e.IdPersona equals pe.IdPersona where pe.login_red == userName && p.A_Adem == year select p ); return(periods); } catch (System.Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public IEnumerable <R_RegistroNotas> GetGrades(string userName, int year, string period) { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); this.db = new SGA_DesarrolloEntities(); db.Configuration.ProxyCreationEnabled = false; var grades = (from g in db.R_RegistroNotas.Include(g => g.R_Cursos) join s in db.R_Estudiantes on g.Estudiante equals s.IdPersona where s.usuario == userName && g.A_Adem == year && g.Trimestre == period select g); return(grades); } catch (System.Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public void ExecutaAssinador() { string ArquivoTemp = ""; var Usuario = new UsuarioInstalador(); var oImpersonate = new Impersonate(); ArquivoTemp = System.AppDomain.CurrentDomain.BaseDirectory + "assinador.application"; WebClient wc = new WebClient(); MemoryStream f = new MemoryStream(wc.DownloadData("http://inbnet/instalacoes/Assinador/asssinador%20da%20Inb.application")); f.Flush(); FileStream fs = new FileStream(ArquivoTemp, FileMode.OpenOrCreate); f.CopyTo(fs); fs.Flush(); fs.Close(); f.Close(); var p = new ProcessStartInfo(ArquivoTemp); using (var exeProcess = Process.Start(p)) { exeProcess.StartInfo.UseShellExecute = false; exeProcess.StartInfo.UserName = UsuarioInstalador.Login; exeProcess.StartInfo.Domain = UsuarioInstalador.Dominio; exeProcess.StartInfo.Password = new SecureString(); foreach (char c in UsuarioInstalador.Senha) { exeProcess.StartInfo.Password.AppendChar(c); } exeProcess.WaitForExit(); } oImpersonate.undoImpersonation(); }
public IEnumerable <P_Notas> GetOldUserMessages(string userName, int last) { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); IEnumerable <P_Notas> messages; SGA_DesarrolloEntities context = new SGA_DesarrolloEntities(); context.Configuration.ProxyCreationEnabled = false; messages = (from n in context.P_Notas join p in context.P_Personas on n.IdPersona equals p.IdPersona where p.login_red == userName && n.idNota <= last select n).Take(50); return(messages); } catch (Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public HttpResponseMessage Post(LogOnModel user) { try { Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user.UserName, user.Password); if (this.ValidateUser(user)) { FormsAuthentication.SetAuthCookie(user.UserName, true); return(Request.CreateResponse(HttpStatusCode.OK, true)); } return(Request.CreateResponse(HttpStatusCode.OK, false)); } catch (DirectoryServicesCOMException dse) { HttpError error = new HttpError(dse.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ")); return(Request.CreateResponse(HttpStatusCode.Unauthorized, error)); } catch (Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
static void Main(string[] args) { Impersonate imp = new Impersonate(); //AddCerts(); imp.ImpersonateAction(".", "testuser777", "test123", AddCerts); Console.WriteLine("Hello World!"); }
public void RestartShoppingCartService() { //--need to impersonate with the user having appropriate rights to start the service Impersonate objImpersonate = new Impersonate(_domainName, _userName, _userPassword); if (objImpersonate.impersonateValidUser()) { var starter = new WindowsServiceStarter(_nameOfService); starter.StopWindowService(); System.Threading.Thread.Sleep(1000); starter.StartWindowService(); objImpersonate.undoImpersonation(); } }
private Document SubmissionToFile(dtoExportSubmission settings) { Document doc = null; System.IO.FileStream stream = null; Impersonate oImpersonate = new Impersonate(); Boolean wasImpersonated = Impersonate.isImpersonated(); try { if (!wasImpersonated && oImpersonate.ImpersonateValidUser() == FileMessage.ImpersonationFailed) { return(null); } else { stream = new System.IO.FileStream(settings.Filename, System.IO.FileMode.Create); if (stream != null) { doc = FileExport(stream); } } } catch (Exception ex) { if (stream != null) { stream.Close(); } if (lm.Comol.Core.File.Exists.File(settings.Filename)) { lm.Comol.Core.File.Delete.File(settings.Filename); } if (!wasImpersonated) { oImpersonate.UndoImpersonation(); } doc = null; } finally { if (!wasImpersonated) { oImpersonate.UndoImpersonation(); } } return(doc); }
//Se Setting == null, viene preso quello di default! private iTextSharp5.text.Document SavePDFtoFile(String storeFileName, lm.Comol.Core.DomainModel.DocTemplateVers.Domain.DTO.ServiceExport.DTO_Settings settings, IList <lm.Comol.Core.DomainModel.DocTemplateVers.Domain.DTO.ServiceExport.DTO_Signature> signatures) { iTS.Document doc = null; System.IO.FileStream stream = null; Impersonate oImpersonate = new Impersonate(); Boolean wasImpersonated = Impersonate.isImpersonated(); try { if (!wasImpersonated && oImpersonate.ImpersonateValidUser() == FileMessage.ImpersonationFailed) { return(null); } else { stream = new System.IO.FileStream(storeFileName, System.IO.FileMode.Create); if (stream != null) { doc = FileExport(settings, stream, signatures); } } } catch (Exception ex) { if (stream != null) { stream.Close(); } if (lm.Comol.Core.File.Exists.File(storeFileName)) { lm.Comol.Core.File.Delete.File(storeFileName); } if (!wasImpersonated) { oImpersonate.UndoImpersonation(); } doc = null; } finally { if (!wasImpersonated) { oImpersonate.UndoImpersonation(); } } return(doc); }
public WindowsImpersonationContext ImpersonateValidUserAndSetThreadPrincipal(string userName, string domain, string password) { WindowsImpersonationContext impersonationContext = null; WindowsIdentity tempWindowsIdentity; var token = IntPtr.Zero; var tokenDuplicate = IntPtr.Zero; IIdentity user; WindowsPrincipal principal; try { if (Convert.ToBoolean(RevertToSelf())) { if (Impersonate.LogonUserA(userName, domain, password, (int)eLogonType.LOGON32_LOGON_INTERACTIVE, (int)eLogonProvider.LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); // apply impersonation to threading user = new WindowsIdentity(token, "NTLM", WindowsAccountType.Normal, true); principal = new WindowsPrincipal((WindowsIdentity)user); Thread.CurrentPrincipal = principal; } } } return(impersonationContext); } catch (Exception ex) { throw ex; } finally { if (!tokenDuplicate.Equals(IntPtr.Zero)) { CloseHandle(tokenDuplicate); } if (!token.Equals(IntPtr.Zero)) { CloseHandle(token); } //return impersonationContext; } }
//This is used to get the list of files names that we can revert the DB in the case of needing to undo a LOCK static public void GetFileNames(DropDownList myDDL) { Impersonate.ImpersonateUser(); string serverPath = "\\\\shares\\TimesheetAttach$\\TS_Config\\"; string[] fileNames = Directory.GetFiles(serverPath, "*.csv"); List <string> reversionList = new List <string> { "---" }; for (int i = 0; i < fileNames.Length; i++) { reversionList.Add(Path.GetFileName(fileNames[i])); } FillDropdown(myDDL, myStringList: reversionList); }
public void DoImpersonate() { Impersonate impersonate = null; try { impersonate = Impersonate.ImpersonateValidUser("yukaritester", "WXP0148D51", "123456"); if (impersonate != null) { Console.WriteLine("Impersonated."); } } finally { if (impersonate != null) { impersonate.Dispose(); } } }
public IEnumerable <VR_Rendimiento_A_Academ> GetVR_Rendimiento_A_Academ() { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); this.db = new SGA_DesarrolloEntities(); return(db.VR_Rendimiento_A_Academ.AsEnumerable()); } catch (System.Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
internal override bool Query() { SQLServerInfo i = new SQLServerInfo(credentials); i.SetInstance(instance); i.Query(); var info = i.GetResults(); SetPermissionNameFilter("IMPERSONATE"); base.Query(); using (SQLConnection sql = new SQLConnection()) { sql.BuildConnectionString(credentials); sql.Connect(); foreach (var j in serverPrivileges) { string query = string.Format("SELECT IS_SRVROLEMEMBER(\'sysadmin\', \'{0}\') as Status", j.ObjectName); foreach (var r in sql.Query(query).AsEnumerable()) { if (!(r["Status"] is DBNull) && 1 == (int)r["Status"]) { var s = new Impersonate { ComputerName = computerName, Instance = instance, Vulnerability = "Excessive Privilege - Impersonate Login", Description = "The current SQL Server login can impersonate other logins. This may allow an authenticated login to gain additional privileges.", Remediation = "Consider using an alterative to impersonation such as signed stored procedures. Impersonation is enabled using a command like: GRANT IMPERSONATE ON Login::sa to [user]. It can be removed using a command like: REVOKE IMPERSONATE ON Login::sa to [user]", Severity = "High", IsVulnerable = "Yes", IsExploitable = "Unknown", Exploited = "No", ExploitCmd = "", Reference = @"https://msdn.microsoft.com/en-us/library/ms181362.aspx", Details = string.Format("{0} can impersonate the {1} SYSADMIN login. This test was ran with the {2} login.", j.GranteeName, j.ObjectName, info.Currentlogin) }; impersonates.Add(s); } } } } return(true); }
public IEnumerable <R_RegistroNotas> GetR_RegistroNotas() { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); this.db = new SGA_DesarrolloEntities(); var r_registronotas = db.R_RegistroNotas.Include(r => r.R_Estudiantes); return(r_registronotas.AsEnumerable()); } catch (System.Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public static Impersonate ImpersonateValidUser(string userName, string domain, string password) { WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; Impersonate retValue = null; try { // 現在偽装していないことを確認。 if (RevertToSelf() == true) { // 偽装するユーザーのユーザー名とパスワードを確認。 if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out token) == true) { // 現在ログイン中のユーザーのコンテキストを複製する。 if (DuplicateToken(token, 2, out tokenDuplicate) == true) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); retValue = new Impersonate(tempWindowsIdentity); if (retValue.impersonationContext == null) { retValue = null; } } } } return(retValue); } finally { // try - finally は2重にするべき。。。 if (!tokenDuplicate.Equals(IntPtr.Zero)) { CloseHandle(tokenDuplicate); } if (!token.Equals(IntPtr.Zero)) { CloseHandle(token); } } }
public R_RegistroNotas GetR_RegistroNotas(int id) { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); this.db = new SGA_DesarrolloEntities(); R_RegistroNotas r_registronotas = db.R_RegistroNotas.Find(id); if (r_registronotas == null) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); } return(r_registronotas); } catch (System.Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public VR_Rendimiento_A_Academ GetVR_Rendimiento_A_Academ(int id) { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); this.db = new SGA_DesarrolloEntities(); VR_Rendimiento_A_Academ vr_rendimiento_a_academ = db.VR_Rendimiento_A_Academ.Find(id); if (vr_rendimiento_a_academ == null) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); } return(vr_rendimiento_a_academ); } catch (System.Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public bool impersonateValidUser(string userName, string domain, string password) { bool impersonateValidUserRet = false; WindowsIdentity tempWindowsIdentity; var token = IntPtr.Zero; var tokenDuplicate = IntPtr.Zero; impersonateValidUserRet = false; if (Convert.ToBoolean(RevertToSelf())) { if (Impersonate.LogonUserA(userName, domain, password, (int)eLogonType.LOGON32_LOGON_NETWORK, (int)eLogonProvider.LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, (int)eImpersonationLevel.SecurityImpersonation, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext is object) { impersonateValidUserRet = true; } } } } if (!tokenDuplicate.Equals(IntPtr.Zero)) { CloseHandle(tokenDuplicate); } if (!token.Equals(IntPtr.Zero)) { CloseHandle(token); } return(impersonateValidUserRet); }
public IEnumerable <P_NotasPublicas> GetOldPublicMessages(int last) { try { NameValueCollection user = HttpUtility.ParseQueryString(Request.RequestUri.Query); Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user["UserName"], user["Password"]); SGA_DesarrolloEntities context = new SGA_DesarrolloEntities(); context.Configuration.ProxyCreationEnabled = false; IEnumerable <P_NotasPublicas> notas; notas = (from pm in context.P_NotasPublicas where pm.Activa == true && pm.idNotasPublicas <= last select pm).Take(50);; return(notas); } catch (Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
private void btnMerge_Click(object sender, System.EventArgs e) { string[] Keys = { "OPEN", "HIGH", "LOW", "CLOSE", "VOLUME", "DATE", "ADJCLOSE" }; string[] ss = tbCSVData.Text.Trim().Split('\n'); int DateIndex = 0; int TickerIndex = -1; string[] ssHeader; string DateFormat; GetFormatInfo(ref DateIndex, ref TickerIndex, out ssHeader, out DateFormat); SortedList slAllSymbol = new SortedList(Comparer.Default); SortedList slOneSymbol; char r = GetSeperator(); for (int i = cbHasHeader.Checked?1:0; i < ss.Length; i++) { string[] sss = ss[i].Trim().Split(r); try { string Ticker = tbSymbol.Text; if (TickerIndex >= 0) { Ticker = sss[TickerIndex]; } slOneSymbol = (SortedList)slAllSymbol[Ticker]; if (Ticker == "") { throw new Exception("Symbol can't be empty!"); } if (slOneSymbol == null) { slOneSymbol = new SortedList(Comparer.Default); slAllSymbol[Ticker] = slOneSymbol; } slOneSymbol[DateTime.ParseExact(sss[DateIndex].Trim(), DateFormat, DateTimeFormatInfo.InvariantInfo) ] = sss; } catch (Exception ex) { throw new Exception(ex.Message + ";" + sss[DateIndex] + ";" + DateFormat); } } lMsg.Text = ""; DBDataManager ddm = new DBDataManager(); try { foreach (string s in slAllSymbol.Keys) { slOneSymbol = (SortedList)slAllSymbol[s]; double[][] ds = new double[7][]; for (int i = 0; i < ds.Length; i++) { ds[i] = new double[slOneSymbol.Count]; for (int j = 0; j < ds[i].Length; j++) { ds[i][j] = double.NaN; } } for (int i = 0; i < slOneSymbol.Count; i++) { ds[5][i] = ((DateTime)slOneSymbol.GetKey(i)).ToOADate(); for (int j = 0; j < ssHeader.Length; j++) { if (j != DateIndex && j != TickerIndex) { int k = Array.IndexOf(Keys, ssHeader[j].ToUpper()); if (k >= 0) { string[] sss = (string[])slOneSymbol.GetByIndex(i); ds[k][i] = double.Parse(sss[j]); } } } for (int j = 0; j < ds.Length; j++) { if (double.IsNaN(ds[j][i])) { ds[j][i] = ds[3][i]; } } } CommonDataProvider cdp = (CommonDataProvider)ddm[s]; CommonDataProvider cdpDelta = new CommonDataProvider(null); cdpDelta.LoadBinary(ds); lMsg.Text += "Symbol:" + s + "; Original data count :" + cdp.Count + "; Merge data count : " + cdpDelta.Count + "; "; cdp.Merge(cdpDelta); lMsg.Text += "New data count : " + cdp.Count + "<br>"; Impersonate.ChangeToAdmin(); Utils.UpdateRealtime(s, cdp); cdp.SaveBinary(DBDataManager.GetHisDataFile(s)); } } catch (Exception ex) { lMsg.Text = ex.Message; } }
static public string CheckStatus(Page currentPage) { using (WindowsIdentity.Impersonate(IntPtr.Zero)) { //This code executes under app pool user string access = ""; List <string> emailList = new List <string>(); string username = currentPage.User.Identity.Name.Replace(@"CCSO\", "").ToUpper(); string serverPath = "\\\\shares\\TimesheetAttach$\\TS_Config\\HREmails.txt"; bool isMaintenanceMode = false; if (ConfigurationManager.AppSettings["MaintenanceMode"].ToString().Equals("On")) { isMaintenanceMode = true; } ArrayList groups = TSADGroups.Groups(username.Substring(username.IndexOf("\\") + 1)); if (!isMaintenanceMode) { Impersonate.ImpersonateUser(); var emails = File.ReadAllLines(serverPath).Where(line => line.Contains("@")); foreach (string emailAddress in emails) { emailList.Add(emailAddress); } Impersonate.impersonationContext.Undo(); //lbluserName.Text = userName1; //Session["Access"] = "Denied"; foreach (string users in emailList) { if (users.Contains(username)) { access = "HRER"; } } for (int y = 0; y < groups.Count; y++) { //if (groups[y].ToString().Contains("Financial Services"))//need group name to look for to be able to edit //groups[y].ToString().Contains("Information Technology Unit") if (groups[y].ToString().Contains("Payroll") /*|| groups[y].ToString().Contains("Information Technology Unit")*/) //need group name to look for to be able to edit { access = "Payroll"; } if ((groups[y].ToString().Contains("Developer Unit") && !currentPage.Request.Url.ToString().Contains("iis2016"))) { access = "Developer"; } if ((groups[y].ToString().Contains("Developer Unit") || groups[y].ToString().Contains("ittechs")) && currentPage.Request.Url.ToString().Contains("iis2016")) { access = "ITTech"; } if (groups[y].ToString().Contains("Command Staff Assistants")) { access = "StaffAssistant"; } } return(access); } else { for (int y = 0; y < groups.Count; y++) { if (groups[y].ToString().Contains("Developer Unit")) { access = "Developer"; break; } else { access = "Denied"; } } return(access); } } }
static public string MergeData(string Symbol, string TextData, string DataFormat, string DateFormat, char Separator, bool HasHeader) { string[] Keys = { "OPEN", "HIGH", "LOW", "CLOSE", "VOLUME", "DATE", "ADJCLOSE" }; string[] ss = TextData.Trim().Split('\n'); int DateIndex = 0; int TickerIndex = -1; string[] ssHeader; //string DateFormat; GetFormatInfo(DataFormat, ref DateIndex, ref TickerIndex, out ssHeader, ref DateFormat); SortedList slAllSymbol = new SortedList(Comparer.Default); SortedList slOneSymbol; //char r = GetSeperator(); for (int i = HasHeader?1:0; i < ss.Length; i++) { string[] sss = ss[i].Trim().Split(Separator); try { string Ticker = Symbol; //tbSymbol.Text; if (TickerIndex >= 0) { Ticker = sss[TickerIndex]; } slOneSymbol = (SortedList)slAllSymbol[Ticker]; if (Ticker == "") { throw new Exception("Symbol can't be empty!"); } if (slOneSymbol == null) { slOneSymbol = new SortedList(Comparer.Default); slAllSymbol[Ticker] = slOneSymbol; } slOneSymbol[DateTime.ParseExact(sss[DateIndex].Trim(), DateFormat, DateTimeFormatInfo.InvariantInfo) ] = sss; } catch (Exception ex) { throw new Exception(ex.Message + ";" + sss[DateIndex] + ";" + DateFormat); } } string Msg = ""; DataManagerBase dmb = Utils.GetDefaultDataManager(); try { foreach (string s in slAllSymbol.Keys) { slOneSymbol = (SortedList)slAllSymbol[s]; double[][] ds = new double[7][]; for (int i = 0; i < ds.Length; i++) { ds[i] = new double[slOneSymbol.Count]; for (int j = 0; j < ds[i].Length; j++) { ds[i][j] = double.NaN; } } for (int i = 0; i < slOneSymbol.Count; i++) { ds[5][i] = ((DateTime)slOneSymbol.GetKey(i)).ToOADate(); for (int j = 0; j < ssHeader.Length; j++) { if (j != DateIndex && j != TickerIndex) { int k = Array.IndexOf(Keys, ssHeader[j].ToUpper()); if (k >= 0) { string[] sss = (string[])slOneSymbol.GetByIndex(i); ds[k][i] = double.Parse(sss[j]); } } } for (int j = 0; j < ds.Length; j++) { if (double.IsNaN(ds[j][i])) { ds[j][i] = ds[3][i]; } } } CommonDataProvider cdp = (CommonDataProvider)dmb[s]; CommonDataProvider cdpDelta = new CommonDataProvider(null); cdpDelta.LoadBinary(ds); Msg += "Symbol:" + s + "; Original data count :" + cdp.Count + "; Merge data count : " + cdpDelta.Count + "; "; cdp.Merge(cdpDelta); Msg += "New data count : " + cdp.Count + "<br>"; Impersonate.ChangeToAdmin(); dmb.SaveData(s, cdp, false); } } catch (Exception ex) { return(ex.Message); } return(Msg); }