//HttpContext context static public void notifyException(Exception ex, HttpContext context) { try{ String texto = getExceptionText(ex, context); using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection())) sendEmail("Erro em IAM", conf.GetItem("to"), texto, false); texto = null; } catch { } }
protected void Page_Load(object sender, EventArgs e) { String html = ""; String error = ""; LoginData login = LoginUser.LogedUser(this); if (login == null) { Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "login2/", false); } else { html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"" + Session["ApplicationVirtualPath"] + "login2/changepassword/\"><div class=\"login_form\">"; if (Request.HttpMethod == "POST") { try { String password = Tools.Tool.TrataInjection(Request["password"]); String password2 = Request["password2"]; if ((password == null) || (password == "")) { error = MessageResource.GetMessage("type_password"); } else if ((password2 == null) || (password2 == "")) { error = MessageResource.GetMessage("type_password_confirm"); } else if (password != password2) { error = MessageResource.GetMessage("password_not_equal"); } else { Int64 enterpriseId = 0; if ((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null)) { enterpriseId = ((EnterpriseData)Page.Session["enterprise_data"]).Id; } using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { UserPasswordStrength usrCheck = new UserPasswordStrength(db.Connection, login.Id); UserPasswordStrengthResult check = usrCheck.CheckPassword(password); if (check.HasError) { if (check.NameError) { error = MessageResource.GetMessage("password_name_part"); } else { String txt = "* " + MessageResource.GetMessage("number_char") + ": " + (!check.LengthError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("uppercase") + ": " + (!check.UpperCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("lowercase") + ": " + (!check.LowerCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("numbers") + ": " + (!check.DigitError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("symbols") + ": " + (!check.SymbolError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")); error = MessageResource.GetMessage("password_complexity") + ": <br />" + txt; } } else { DataTable c = db.Select("select * from entity where deleted = 0 and id = " + login.Id); if ((c != null) && (c.Rows.Count > 0)) { //Verifica a senha atual using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId)) using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(c.Rows[0]["password"].ToString()))) { using (SqlConnection conn1 = IAMDatabase.GetWebConnection()) using (EnterpriseKeyConfig sk1 = new EnterpriseKeyConfig(conn1, enterpriseId)) using (CryptApi cApi1 = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password))) { DbParameterCollection pPar = new DbParameterCollection(); String b64 = Convert.ToBase64String(cApi1.ToBytes()); pPar.Add("@password", typeof(String), b64.Length).Value = b64; db.ExecuteNonQuery("update entity set password = @password, change_password = getdate() , recovery_code = null, must_change_password = 0 where id = " + login.Id, CommandType.Text, pPar); } db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, login.Id, 0, "Password changed through logged user", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} "); //Cria o pacote com os dados atualizados deste usuário //Este processo visa agiliar a aplicação das informações pelos plugins db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + login.Id + ")", CommandType.Text, null); //Mata a sessão //Session.Abandon(); Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "login2/passwordchanged/", false); } } else { error = MessageResource.GetMessage("internal_error"); } } } } } catch (Exception ex) { Tools.Tool.notifyException(ex); error = MessageResource.GetMessage("internal_error") + ": " + ex.Message; } } html += " <ul>"; html += " <li>"; html += " <p style=\"width:270px;padding:0 0 20px 0;color:#000;\">" + MessageResource.GetMessage("password_expired_text") + "</p>"; html += " </li>"; html += " <li>"; html += " <span class=\"inputWrap\">"; html += " <input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password") + "\" onkeyup=\"cas.passwordStrength('#password');\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />"; html += " <span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>"; html += " </span>"; html += " </li>"; html += " <li>"; html += " <span class=\"inputWrap\">"; html += " <input type=\"password\" id=\"password2\" tabindex=\"1\" name=\"password2\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password_confirm") + "\" onfocus=\"$('#password2').addClass('focus');\" onblur=\"$('#password2').removeClass('focus');\" />"; html += " <span id=\"ph_passwordIcon\" onclick=\"$('#password2').focus();\"></span>"; html += " </span>"; html += " </li>"; html += " <li>"; html += " <div id=\"passwordStrength\"><span>" + MessageResource.GetMessage("password_strength") + ": " + MessageResource.GetMessage("unknow") + "</span><div class=\"bar\"></div></div>"; html += " </li>"; if (error != "") { html += " <li><div class=\"error-box\">" + error + "</div>"; } html += " <li>"; html += " <span class=\"forgot\"> <a href=\"" + Session["ApplicationVirtualPath"] + "logout/\">" + MessageResource.GetMessage("cancel") + "</a> </span>"; html += " <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("change_password") + "</button>"; html += " </li>"; html += " </ul>"; html += "</div></form>"; holderContent.Controls.Add(new LiteralControl(html)); } }
static public LoginResult Grant(Page page, String username, String password) { try { if ((username == null) || (username.Trim() == "") || (username == password) || (username.Trim() == "")) { return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"))); } Int64 enterpriseId = 0; if ((page.Session["enterprise_data"]) != null && (page.Session["enterprise_data"] is EnterpriseData)) { enterpriseId = ((EnterpriseData)page.Session["enterprise_data"]).Id; } String svc = page.Request.QueryString["service"].TrimEnd("/".ToCharArray()).Replace("https://", "//").Replace("http://", "//").Trim(); DbParameterCollection par = new DbParameterCollection();; par.Add("@login", typeof(String), username.Length).Value = username; par.Add("@svc", typeof(String), svc.Length).Value = svc; using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { DataTable tmp = db.ExecuteDataTable("select distinct l.id, l.alias, l.full_name, l.login, l.enterprise_id, l.password, l.must_change_password, s.id as service_id, c.service_uri, c.grant_ticket, c.long_ticket from vw_entity_logins l inner join cas_service s on l.enterprise_id = s.enterprise_id left join (select * from cas_entity_ticket c1 inner join cas_service s on s.id = c1.service_id) c on l.id = c.entity_id and c.service_uri = @svc where l.deleted = 0 and l.locked = 0 and (l.login = @login or l.value = @login) and s.service_uri = @svc", CommandType.Text, par); if ((tmp != null) && (tmp.Rows.Count > 0)) { foreach (DataRow dr in tmp.Rows) { using (SqlConnection conn = IAMDatabase.GetWebConnection()) using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(conn, enterpriseId)) using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString()))) if (Encoding.UTF8.GetString(cApi.clearData) == password) { //Realiza o login LoginData l = new LoginData(); l.Alias = tmp.Rows[0]["alias"].ToString(); l.FullName = tmp.Rows[0]["full_name"].ToString(); l.Login = tmp.Rows[0]["login"].ToString(); l.Id = (Int64)tmp.Rows[0]["id"]; l.EnterpriseId = (Int64)tmp.Rows[0]["enterprise_id"]; l.CASGrantTicket = CASTicket.Generate(); l.CASLongTicket = CASTicket.Generate(); if (tmp.Rows[0]["grant_ticket"] != DBNull.Value) { l.CASGrantTicket = tmp.Rows[0]["grant_ticket"].ToString(); } if (tmp.Rows[0]["long_ticket"] != DBNull.Value) { l.CASLongTicket = tmp.Rows[0]["long_ticket"].ToString(); } try { page.Response.Cookies.Remove("TGC-SafeID"); page.Response.Cookies.Remove("TGT-SafeID"); } catch { } try { //Adiciona o cookie do TGC HttpCookie cookie = new HttpCookie("TGC-SafeID"); //cookie.Domain = page.Request.Url.Host; cookie.Path = "/cas"; cookie.Value = l.CASGrantTicket; DateTime dtNow = DateTime.Now; TimeSpan tsMinute = new TimeSpan(30, 0, 0, 0); cookie.Expires = dtNow + tsMinute; //Adiciona o cookie page.Response.Cookies.Add(cookie); } catch { } try { //Adiciona o cookie do TGC HttpCookie cookie = new HttpCookie("TGT-SafeID"); //cookie.Domain = page.Request.Url.Host; cookie.Path = "/cas"; cookie.Value = l.CASLongTicket; DateTime dtNow = DateTime.Now; TimeSpan tsMinute = new TimeSpan(30, 0, 0, 0); cookie.Expires = dtNow + tsMinute; //Adiciona o cookie page.Response.Cookies.Add(cookie); } catch { } db.ExecuteNonQuery("update entity set last_login = getdate() where id = " + l.Id, CommandType.Text, null); if (tmp.Rows[0]["service_uri"] == DBNull.Value) { db.ExecuteNonQuery("insert into cas_entity_ticket ([entity_id],[service_id],[grant_ticket],[long_ticket],[create_by_credentials]) VALUES (" + l.Id + ", " + tmp.Rows[0]["service_id"].ToString() + ", '" + l.CASGrantTicket + "', '" + l.CASLongTicket + "',1)", CommandType.Text, null); } else { db.ExecuteNonQuery("update cas_entity_ticket set grant_ticket = '" + l.CASGrantTicket + "', long_ticket = '" + l.CASLongTicket + "', expire_date = dateadd(day,1,getdate()), create_by_credentials = 1 where entity_id = " + l.Id + " and service_id = " + tmp.Rows[0]["service_id"].ToString(), CommandType.Text, null); } db.AddUserLog(LogKey.User_Logged, null, "CAS", UserLogLevel.Info, 0, 0, 0, 0, 0, l.Id, 0, MessageResource.GetMessage("user_logged") + " " + Tools.Tool.GetIPAddress(), "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} "); return(new LoginResult(true, "User OK", (Boolean)tmp.Rows[0]["must_change_password"], l)); break; } else { db.AddUserLog(LogKey.User_WrongPassword, null, "CAS", UserLogLevel.Info, 0, 0, 0, 0, 0, (Int64)tmp.Rows[0]["id"], 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} "); } } return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"))); } else { db.AddUserLog(LogKey.User_WrongUserAndPassword, null, "CAS", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"username\":\"" + username.Replace("'", "").Replace("\"", "") + "\", \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} "); return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"))); } } } catch (Exception ex) { Tools.Tool.notifyException(ex, page); return(new LoginResult(false, "Internal error")); } finally { } }
static public void notifyException(Exception ex) { try { String texto = ""; texto += "----------------------------------" + Environment.NewLine; texto += DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + Environment.NewLine + Environment.NewLine; texto += "----------------------------------" + Environment.NewLine; texto += ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine; if (ex is HttpException) { HttpException httpEx = (HttpException)ex; texto += "HttpException: " + httpEx.GetHttpCode() + Environment.NewLine + Environment.NewLine; } if (ex.InnerException != null) { texto += "InnerException: " + ex.InnerException.Message + Environment.NewLine + ex.InnerException.StackTrace + Environment.NewLine + Environment.NewLine; if (ex.InnerException.InnerException != null) { texto += "InnerException: " + ex.InnerException.InnerException.Message + Environment.NewLine + ex.InnerException.InnerException.StackTrace + Environment.NewLine + Environment.NewLine; } } try { texto += Environment.NewLine; texto += "----------------------------------" + Environment.NewLine; texto += "HostingEnvironment Properties" + Environment.NewLine; texto += "Application ID: " + HostingEnvironment.ApplicationID; texto += "Application Physical Path: " + HostingEnvironment.ApplicationPhysicalPath; texto += "Application Virtual Path: " + HostingEnvironment.ApplicationVirtualPath; texto += "Site Name: " + HostingEnvironment.SiteName; texto += Environment.NewLine; } catch { } texto += Environment.NewLine; texto += "----------------------------------" + Environment.NewLine; try { texto += "Windows User: "******"plugins")); //texto += "Physical Directory: " + WindowsIdentity.GetCurrent().Name + Environment.NewLine; } catch { } try { texto += "Environment Directory: " + Environment.CurrentDirectory + Environment.NewLine; } catch { } using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection())) sendEmail("Erro em IAM", conf.GetItem("to"), texto, false); texto = null; } catch { } }
protected void Page_Load(object sender, EventArgs e) { Request.InputStream.Position = 0; try { JSONRequest req = JSON.GetRequest(Request.InputStream); using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { ProxyConfig config = new ProxyConfig(true); config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host); if (config.fqdn != null) //Encontrou o proxy { DirectoryInfo inDir = null; using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection())) inDir = new DirectoryInfo(c.GetItem("inboundFiles")); if (!inDir.Exists) { inDir.Create(); } req.enterpriseid = ((EnterpriseData)Page.Session["enterprise_data"]).Id.ToString(); String filename = config.proxy_name + "-" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".iamreq"; if (String.IsNullOrEmpty(req.filename)) { req.filename = "Empty"; } StringBuilder trackData = new StringBuilder(); trackData.AppendLine("Proxy: " + req.host); trackData.AppendLine("Enterprise ID: " + req.enterpriseid); trackData.AppendLine("Proxy filename: " + req.filename); trackData.AppendLine("Saved filename: " + filename); UserLogLevel level = UserLogLevel.Info; trackData.AppendLine(""); trackData.AppendLine("Checking package..."); if (String.IsNullOrEmpty(req.data)) { throw new Exception("Request data is empty"); } Byte[] rData = Convert.FromBase64String(req.data); if (!String.IsNullOrEmpty(req.sha1hash)) { if (!CATools.SHA1CheckHash(rData, req.sha1hash)) { throw new Exception("SHA1 Checksum is not equal"); } } String type = ""; try { JsonGeneric jData = new JsonGeneric(); try { String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); if (String.IsNullOrEmpty(config.server_pkcs12_cert)) { throw new Exception("Server PKCS12 from proxy config is empty"); } using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), rData)) jData.FromJsonBytes(cApi.clearData); } catch (Exception ex) { jData = null; trackData.AppendLine("Error decrypting package data for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message); #if DEBUG trackData.AppendLine(ex.StackTrace); #endif } if (jData != null) { #if DEBUG trackData.AppendLine(""); trackData.AppendLine("Request data:"); trackData.AppendLine(jData.ToJsonString()); trackData.AppendLine(""); #endif type = jData.function; trackData.AppendLine("Type: " + type); trackData.AppendLine("Data array length: " + (jData.data == null ? "0" : jData.data.Count.ToString())); if (type.ToLower() == "processimportv2") { Int32 d = 1; foreach (String[] dr in jData.data) { try { Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin"); Int32 pkgCol = jData.GetKeyIndex("package"); if (resourcePluginCol == -1) { trackData.AppendLine("[Package data " + d + "] Erro finding column 'resource_plugin'"); } if (pkgCol == -1) { trackData.AppendLine("[Package data " + d + "] Erro finding column 'package'"); } if ((resourcePluginCol != -1) && (pkgCol != -1)) { PluginConnectorBaseImportPackageUser pkg = JSON.DeserializeFromBase64 <PluginConnectorBaseImportPackageUser>(dr[pkgCol]); trackData.AppendLine("[Package data " + d + "] Import id: " + pkg.importId); trackData.AppendLine("[Package data " + d + "] Package id: " + pkg.pkgId); Int64 trackId = 0; try { String tpkg = JSON.Serialize2(pkg); DbParameterCollection par = new DbParameterCollection(); par.Add("@entity_id", typeof(Int64)).Value = 0; par.Add("@date", typeof(DateTime)).Value = pkg.GetBuildDate(); par.Add("@flow", typeof(String)).Value = "inbound"; par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId; par.Add("@filename", typeof(String)).Value = req.filename; par.Add("@package", typeof(String), tpkg.Length).Value = tpkg; trackId = database.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null); trackData.AppendLine("[Package data " + d + "] Package track id: " + trackId); tpkg = null; if (trackId > 0) { database.AddPackageTrack(trackId, "ProxyAPI", "Package received from proxy and saved at " + filename); } } catch (Exception ex3) { trackData.AppendLine("[Package data " + d + "] Erro generating package track: " + ex3.Message); } pkg.Dispose(); pkg = null; } } catch (Exception ex2) { trackData.AppendLine("[Package data " + d + "] Erro parsing package data " + ex2.Message); } d++; } } } } catch (Exception ex1) { trackData.AppendLine("Erro parsing package " + ex1.Message); level = UserLogLevel.Error; } database.AddUserLog(LogKey.API_Log, DateTime.Now, "ProxyAPI", level, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "File received from proxy " + req.host + (String.IsNullOrEmpty(type) ? "" : " (" + type + ")"), trackData.ToString()); File.WriteAllBytes(Path.Combine(inDir.FullName, filename), Encoding.UTF8.GetBytes(JSON.Serialize <JSONRequest>(req))); ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", "Request received and proxy finded (" + (req.data != null ? req.data.Length.ToString() : "0") + ")"))); } } } catch (Exception ex) { Tools.Tool.notifyException(ex); throw ex; } }
static public void sendEmail(String Subject, String to, String replyTo, String body, Boolean isHTML) { using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection())) { MailMessage mail = new MailMessage(); mail.From = new MailAddress(conf.GetItem("mailFrom")); String tTo = to.Replace(";", ",") + ","; foreach (String t in tTo.Split(",".ToCharArray())) { if (!String.IsNullOrEmpty(t)) { mail.To.Add(new MailAddress(t)); } } if (mail.To.Count == 0) { mail.To.Add(new MailAddress("*****@*****.**")); } mail.Subject = Subject; mail.IsBodyHtml = isHTML; mail.Body = body; if (replyTo != null) { try { mail.ReplyTo = new MailAddress(replyTo); } catch { } } SmtpClient client = new SmtpClient(); client.Host = conf.GetItem("smtpServer"); client.Port = 25; client.EnableSsl = false; try { Int32 port = Int32.Parse(conf.GetItem("smtpPort")); switch (port) { case 587: client.EnableSsl = true; break; case 465: client.EnableSsl = true; break; } } catch { } client.Credentials = new System.Net.NetworkCredential(conf.GetItem("username"), conf.GetItem("password")); System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }); client.Send(mail); client = null; mail = null; } }
protected void Page_Load(object sender, EventArgs e) { WebJsonResponse ret = null; LoginData login = LoginUser.LogedUser(this); String err = ""; if (!EnterpriseIdentify.Identify(this, false, out err)) //Se houver falha na identificação da empresa finaliza a resposta { ret = new WebJsonResponse("", err, 3000, true); } else if (login == null) { ret = new WebJsonResponse("", MessageResource.GetMessage("expired_session"), 3000, true, "/login/"); } else { try { Int64 enterpriseId = 0; if ((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null)) { enterpriseId = ((EnterpriseData)Page.Session["enterprise_data"]).Id; } String currentPassword = Tools.Tool.TrataInjection(Request["current_password"]); String password = Tools.Tool.TrataInjection(Request["password"]); String password2 = Request["password2"]; if ((currentPassword == null) || (currentPassword == "")) { ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_current"), 3000, true); } else if ((password == null) || (password == "")) { ret = new WebJsonResponse("", MessageResource.GetMessage("type_password"), 3000, true); } else if ((password2 == null) || (password2 == "")) { ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_confirm"), 3000, true); } else if (password != password2) { ret = new WebJsonResponse("", MessageResource.GetMessage("password_not_equal"), 3000, true); } else { using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { try { UserPasswordStrength usrCheck = new UserPasswordStrength(db.Connection, login.Id); UserPasswordStrengthResult check = usrCheck.CheckPassword(password); if (check.HasError) { if (check.NameError) { ret = new WebJsonResponse("", MessageResource.GetMessage("password_name_part"), 3000, true); } else { String txt = "* " + MessageResource.GetMessage("number_char") + ": " + (!check.LengthError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("uppercase") + ": " + (!check.UpperCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("lowercase") + ": " + (!check.LowerCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("numbers") + ": " + (!check.DigitError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />"; txt += "* " + MessageResource.GetMessage("symbols") + ": " + (!check.SymbolError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")); ret = new WebJsonResponse("", MessageResource.GetMessage("password_complexity") + ": <br />" + txt, 5000, true); } } else { DataTable c = db.Select("select * from entity where deleted = 0 and id = " + login.Id); if ((c != null) && (c.Rows.Count > 0)) { //Verifica a senha atual using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId)) using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(c.Rows[0]["password"].ToString()))) if (Encoding.UTF8.GetString(cApi.clearData) != currentPassword) { ret = new WebJsonResponse("", MessageResource.GetMessage("current_password_invalid"), 3000, true); } else { using (SqlConnection conn1 = IAMDatabase.GetWebConnection()) using (EnterpriseKeyConfig sk1 = new EnterpriseKeyConfig(conn1, enterpriseId)) using (CryptApi cApi1 = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password))) { DbParameterCollection pPar = new DbParameterCollection();; String b64 = Convert.ToBase64String(cApi1.ToBytes()); pPar.Add("@password", typeof(String), b64.Length).Value = b64; db.ExecuteNonQuery("update entity set password = @password, change_password = getdate() , recovery_code = null, must_change_password = 0 where id = " + login.Id, CommandType.Text, pPar); } db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, login.Id, 0, "Password changed through autoservice logged user", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} "); //Cria o pacote com os dados atualizados deste usuário //Este processo visa agiliar a aplicação das informações pelos plugins db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + login.Id + ")", CommandType.Text, null); /* * IAMDeploy deploy = null; * * using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection())) * deploy = new IAMDeploy("WebServer", DB.GetConnectionString(), conf.GetItem("outboundFiles")); * * if (deploy != null) * deploy.DeployOne(login.Id);*/ String html = ""; html += "<div class=\"no-tabs pb10\">"; html += " <div class=\"form-group\">"; html += " <h1>" + MessageResource.GetMessage("password_changed_sucessfully") + "</h1> "; html += " </div>"; html += " <div class=\"form-group\"><span class=\"text-message\">" + MessageResource.GetMessage("password_changed_text") + "</span></div>"; html += "</div>"; ret = new WebJsonResponse("#pwdForm", html); } } else { ret = new WebJsonResponse("", "Internal error", 3000, true); } } } finally { } } } } catch (Exception ex) { Tools.Tool.notifyException(ex); throw ex; } } if (ret != null) { ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON())); } }
protected void Page_Load(object sender, EventArgs e) { Request.InputStream.Position = 0; try { JSONRequest req = JSON.GetRequest(Request.InputStream); using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { ProxyConfig config = new ProxyConfig(); config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host); if (config.fqdn != null) //Encontrou o proxy { DirectoryInfo outDir = null; using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection())) outDir = new DirectoryInfo(Path.Combine(c.GetItem("outboundFiles"), config.proxyID + "_" + config.proxy_name)); if (!outDir.Exists) { outDir.Create(); } if ((req.data != null) && (req.data != "")) { //Recebeu o nome do arquivo, envia o unico arquivo FileInfo fName = null; try { fName = new FileInfo(Path.Combine(outDir.FullName, req.data.Trim("..\\/".ToCharArray()))); } catch { ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Filename is invalid", ""))); return; } if (fName.Exists) { try { fName.Delete(); ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", "Notify received"))); //Verifica se pode remover o diretório try { if (outDir.GetFiles("*.iamdat", SearchOption.AllDirectories).Length == 0) { outDir.Delete(true); } } catch { } } catch (Exception ex) { ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Error deleting file " + fName.Name + ", " + ex.Message, ""))); } } else { ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "File not found '" + req.data + "'", ""))); } } } } } catch (Exception ex) { Tools.Tool.notifyException(ex); throw ex; } }
protected void Page_Load(object sender, EventArgs e) { WebJsonResponse contentRet = null; String action = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["action"])) { action = (String)RouteData.Values["action"]; } Int64 pluginId = 0; if ((action != "add_license") && (action != "upload_item_template") && (action != "upload") && (action != "add_new")) { try { pluginId = Int64.Parse((String)RouteData.Values["id"]); if (pluginId < 0) { pluginId = 0; } } catch { } if (pluginId == 0) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true); action = ""; } } Int64 enterpriseId = 0; if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData)) { enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id; } String rData = ""; //SqlConnection //conn = DB.GetConnection(); String jData = ""; try { switch (action) { case "upload_item_template": String id = Request.Form["id"]; String file = Request.Form["file"]; String tSize = Request.Form["size"]; if (String.IsNullOrEmpty(id)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else if (String.IsNullOrEmpty(file)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else if (String.IsNullOrEmpty(tSize)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else { String userHtmlTemplate = "<div id=\"file{0}\" data-id=\"{0}\" data-name=\"{1}\" class=\"app-list-item file-item\">"; userHtmlTemplate += "<div class=\"form-content\"><input type=\"hidden\" name=\"file_name_{0}\" value=\"{1}\">"; userHtmlTemplate += "<input type=\"hidden\" name=\"{1}\" value=\"{0}\"></div>"; userHtmlTemplate += "<table>"; userHtmlTemplate += " <tbody>"; userHtmlTemplate += " <tr>"; userHtmlTemplate += " <td class=\"colfull\">"; userHtmlTemplate += " <div class=\"title\"><span class=\"name\" id=\"file_name_{0}\" data-id=\"{0}\">{1}</span><div class=\"clear-block\"></div></div>"; userHtmlTemplate += " <div class=\"description\">{2}</div></div>"; userHtmlTemplate += " </td>"; userHtmlTemplate += " </tr>"; userHtmlTemplate += " </tbody>"; userHtmlTemplate += "</table></div>"; String infoTemplate = "<div class=\"line\">"; infoTemplate += "<label>{1}</label>"; infoTemplate += "<span class=\"no-edit {0}\">{2}</span></div>"; String desc = ""; desc += String.Format(infoTemplate, "status", "Status", "Enviando"); String tHtml = String.Format(userHtmlTemplate, id, file, desc); contentRet = new WebJsonResponse("#" + id, tHtml); } break; case "upload": MultipartFormDataParser mp = new MultipartFormDataParser(Request.InputStream); List <String> fls = new List <String>(); String infoTemplate2 = "<div class=\"line\">"; infoTemplate2 += "<label>{1}</label>"; infoTemplate2 += "<span class=\"no-edit {0}\">{2}</span></div>"; // Loop through all the files foreach (FilePart mpF in mp.Files) { try { String d = ""; try { Byte[] rawAssembly = new Byte[mpF.Data.Length]; mpF.Data.Read(rawAssembly, 0, rawAssembly.Length); IAMKeyData memKey = null; String fileData = Convert.ToBase64String(rawAssembly); try { memKey = IAMKey.ExtractFromCert(fileData); } catch { } if (memKey != null) { d += String.Format(infoTemplate2, "", "Nome", mpF.FileName); d += String.Format(infoTemplate2, "", "Tamanho", mpF.Data.Length + " bytes"); Boolean useLicense = false; if (memKey.IsServerKey) { d += String.Format(infoTemplate2, "", "Definitiva?", (memKey.IsTemp ? MessageResource.GetMessage("no") : MessageResource.GetMessage("yes"))); if (memKey.IsTemp) { d += String.Format(infoTemplate2, "", "Expiração", (memKey.TempDate.HasValue ? MessageResource.FormatDate(memKey.TempDate.Value, true) : "não definido")); } d += String.Format(infoTemplate2, "", "Entidades", (memKey.NumLic == 0 ? MessageResource.GetMessage("unlimited") : memKey.NumLic.ToString())); String installKey = ""; using (IAM.Config.ServerKey2 sk = new IAM.Config.ServerKey2(IAMDatabase.GetWebConnection())) installKey = sk.ServerInstallationKey.AbsoluteUri; d += String.Format(infoTemplate2, "", "Chave de instalação", (memKey.InstallKey == installKey ? "Válida" : "Inválida")); if (memKey.InstallKey == installKey) { if (!memKey.IsTemp) { useLicense = true; } else if ((memKey.IsTemp) && (memKey.TempDate.Value.CompareTo(DateTime.Now) > 0)) { useLicense = true; } } } else { d += String.Format(infoTemplate2, "", "Status", "Licença inválida"); } if (useLicense) { d += "<input type=\"hidden\" name=\"key_data\" value=\"" + fileData + "\">"; } /* * if (p2.Count > 0) * d += String.Format(infoTemplate2, "", "Plugins", String.Join(", ", p2)); * else * d += String.Format(infoTemplate2, "", "Plugins", "Nenhum plugin encontrado no arquivo enviado"); * * if (p2.Count > 0) * { * using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) * { * DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly in ('" + String.Join("','", p2) + "') or uri in ('" + String.Join("','", p2Uri) + "'))"); * * if (dt.Rows.Count > 0) * throw new Exception("Plugin/uri ja cadastrado no sistema"); * } * * FileInfo newFile = new FileInfo(Path.Combine(pluginsDir.FullName, mpF.FileName)); * if (newFile.Exists) * newFile.Delete(); * File.WriteAllBytes(newFile.FullName, rawAssembly); * }*/ } else { d += String.Format(infoTemplate2, "", "Status", "Arquivo válido"); } } catch (Exception ex) { d = String.Format(infoTemplate2, "", "Status", "Erro ao realizar o upload"); d += String.Format(infoTemplate2, "", "Informação do erro", ex.Message); } fls.Add(JSON.Serialize2(new { name = mpF.FileName, html = d })); } catch { fls.Add(JSON.Serialize2(new { name = mpF.FileName, error = "Erro enviando o arquivo" })); } } Retorno.Controls.Add(new LiteralControl("{\"files\": [" + String.Join(",", fls) + "]}")); contentRet = null; break; case "add_new": String key_data = ""; key_data = Request.Form["key_data"]; if (!String.IsNullOrEmpty(key_data)) { IAMKeyData memKey = null; try { memKey = IAMKey.ExtractFromCert(key_data); } catch { } if (memKey != null) { Boolean useLicense = false; if (memKey.IsServerKey) { String installKey = ""; using (IAM.Config.ServerKey2 sk = new IAM.Config.ServerKey2(IAMDatabase.GetWebConnection())) installKey = sk.ServerInstallationKey.AbsoluteUri; if (memKey.InstallKey == installKey) { if (!memKey.IsTemp) { useLicense = true; } else if ((memKey.IsTemp) && (memKey.TempDate.Value.CompareTo(DateTime.Now) > 0)) { useLicense = true; } } if (useLicense) { using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { db.openDB(); Object trans = db.BeginTransaction(); try { db.ExecuteNonQuery("delete from license where enterprise_id = " + enterpriseId, CommandType.Text, null, trans); using (DbParameterCollection par = new DbParameterCollection()) { par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@license", typeof(String)).Value = key_data; db.ExecuteNonQuery("insert into license (enterprise_id,license_data) VALUES(@enterprise_id,@license)", CommandType.Text, par, trans); } db.Commit(); contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/license/"); } catch (Exception ex) { db.Rollback(); contentRet = new WebJsonResponse("", "Falha ao aplicar a licença", 5000, true); } } } else { contentRet = new WebJsonResponse("", "Licença inválida", 5000, true); } } else { contentRet = new WebJsonResponse("", "Licença inválida", 5000, true); } } } else { contentRet = new WebJsonResponse("", "Nenhuma licença válida encontrada para aplicar", 5000, true); } break; } } catch (Exception ex) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } finally { } if (contentRet != null) { if (!String.IsNullOrWhiteSpace((String)Request["cid"])) { contentRet.callId = (String)Request["cid"]; } Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON())); } }
protected void Page_Load(object sender, EventArgs e) { WebJsonResponse contentRet = null; Int64 enterpriseId = 0; if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData)) { enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id; } String area = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"])) { area = (String)RouteData.Values["area"]; } Int64 proxyId = 0; try { proxyId = Int64.Parse((String)RouteData.Values["id"]); if (proxyId < 0) { proxyId = 0; } } catch { } if (proxyId == 0) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("proxy_not_found"), 3000, true); area = ""; } String rData = ""; String jData = ""; ProxyGetResult retProxy = null; try { rData = SafeTrend.Json.JSON.Serialize2(new { jsonrpc = "1.0", method = "proxy.get", parameters = new { proxyid = proxyId }, id = 1 }); jData = ""; using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData); if (String.IsNullOrWhiteSpace(jData)) { throw new Exception(""); } retProxy = JSON.Deserialize <ProxyGetResult>(jData); if (retProxy == null) { //error = MessageResource.GetMessage("proxy_not_found"); //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true); } else if (retProxy.error != null) { //error = retProxy.error.data; retProxy = null; } else if (retProxy.result == null || retProxy.result.info == null) { //error = MessageResource.GetMessage("proxy_not_found"); retProxy = null; } else { //menu3.Name = retProxy.result.info.name; } } catch (Exception ex) { //error = MessageResource.GetMessage("api_error"); Tools.Tool.notifyException(ex, this); retProxy = null; //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } try { switch (area) { case "download": if (retProxy != null) { DirectoryInfo tempPath = null; DirectoryInfo proxyPath = null; try { //Cria o diretório temporário tempPath = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); proxyPath = new DirectoryInfo(Path.Combine(tempPath.FullName, "proxies\\" + enterpriseId + "_" + retProxy.result.info.name)); if (!proxyPath.Exists) { proxyPath.Create(); } //Realiza a leitura dos arquivos originais Byte[] multProxy = File.ReadAllBytes(Path.Combine(Request.PhysicalApplicationPath, "_data\\multproxy.zip")); Byte[] proxy = File.ReadAllBytes(Path.Combine(Request.PhysicalApplicationPath, "_data\\proxy.zip")); //Descompacta os zips em uma estrutura temporária ZIPUtil.DecompressData(multProxy, tempPath); ZIPUtil.DecompressData(proxy, proxyPath); //Cria o arquivo de configuração do proxy String config = ""; config += "server=" + Request.Url.Host + (Request.Url.Port != 80 && Request.Url.Port != 443 ? ":" + Request.Url.Port : "") + Environment.NewLine; config += "usehttps=" + (Tools.Tool.IsUsingHTTPS() ? "1" : "0") + Environment.NewLine; config += "hostname=" + retProxy.result.info.name + Environment.NewLine; //Resgata os dados de certificado using (ProxyConfig cfg = new ProxyConfig()) { cfg.GetDBConfig(IAMDatabase.GetWebConnection(), enterpriseId, retProxy.result.info.name); config += "c1=" + cfg.server_cert + Environment.NewLine; config += "c2=" + cfg.client_cert + Environment.NewLine; } File.WriteAllText(Path.Combine(proxyPath.FullName, "proxy.conf"), config, Encoding.UTF8); //Cria o arquivo zip com os dados e retorna Byte[] bRet = ZIPUtil.Compress(tempPath); Response.Clear(); Response.ContentType = "application/zip"; Response.AddHeader("Content-Disposition", "attachment; filename=IAMProxy.zip"); Response.AddHeader("Content-Length", bRet.Length.ToString()); Response.Status = "200 OK"; Response.StatusCode = 200; Response.OutputStream.Write(bRet, 0, bRet.Length); Response.OutputStream.Flush(); } catch (Exception ex) { Response.Status = "500 Internal Error"; Response.StatusCode = 500; } finally { try { if (tempPath != null) { tempPath.Delete(true); } } catch { } } contentRet = null; } break; } } catch (Exception ex) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } if (contentRet != null) { if (!String.IsNullOrWhiteSpace((String)Request["cid"])) { contentRet.callId = (String)Request["cid"]; } Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON())); } }
protected void Page_Load(object sender, EventArgs e) { Request.InputStream.Position = 0; try { JSONRequest req = JSON.GetRequest(Request.InputStream); using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { ProxyConfig config = new ProxyConfig(); config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host); if (config.fqdn != null) //Encontrou o proxy { DirectoryInfo outDir = null; using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection())) outDir = new DirectoryInfo(Path.Combine(c.GetItem("outboundFiles"), config.proxyID + "_" + config.proxy_name)); if (!outDir.Exists) { outDir.Create(); } if ((req.data != null) && (req.data != "")) { //Recebeu o nome do arquivo, envia o unico arquivo FileInfo fName = null; try { fName = new FileInfo(Path.Combine(outDir.FullName, req.data.Trim("..\\/".ToCharArray()))); } catch { ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Filename is invalid", ""))); return; } if (fName.Exists) { try { Byte[] fData = File.ReadAllBytes(fName.FullName); ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", Convert.ToBase64String(fData)))); try { DbParameterCollection par = new DbParameterCollection(); par.Add("@filename", typeof(String)).Value = fName.FullName; Int64 packageTrackId = database.ExecuteScalar <Int64>("select id from st_package_track where flow = 'deploy' and filename = @filename", System.Data.CommandType.Text, par, null); par = new DbParameterCollection(); par.Add("@package_id", typeof(Int64)).Value = packageTrackId; par.Add("@source", typeof(String)).Value = "proxy"; par.Add("@text", typeof(String)).Value = "Proxy Downloaded file from IP " + Tools.Tool.GetIPAddress(); database.ExecuteNonQuery("insert into st_package_track_history ([package_id] ,[source] ,[text]) values (@package_id ,@source ,@text)", System.Data.CommandType.Text, par, null); } catch { } } catch (Exception ex) { ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Error loading file " + fName.Name + ", " + ex.Message, ""))); } } else { ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "File not found '" + req.data + "'", ""))); } } else { List <FileInfo> files = new List <FileInfo>(); foreach (DirectoryInfo d in outDir.GetDirectories()) { files.AddRange(d.GetFiles("*.iamdat", SearchOption.AllDirectories)); } JsonGeneric list = new JsonGeneric(); list.fields = new String[] { "name" }; //Envia a listagem dos arquivos foreach (FileInfo f in files) { list.data.Add(new String[] { f.FullName.Replace(outDir.FullName, "").Trim("\\/ ".ToCharArray()) }); } ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", list.ToJsonString()))); } //File.WriteAllBytes(Path.Combine(pluginsDir.FullName, config.fqdn + "-" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".iamreq"), Encoding.UTF8.GetBytes(JSON.Serialize<JSONRequest>(req))); } } } catch (Exception ex) { Tools.Tool.notifyException(ex); throw ex; } }
protected void Page_Load(object sender, EventArgs e) { WebJsonResponse contentRet = null; String action = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["action"])) { action = (String)RouteData.Values["action"]; } Int64 pluginId = 0; if ((action != "add_plugin") && (action != "upload_item_template") && (action != "upload") && (action != "add_new")) { try { pluginId = Int64.Parse((String)RouteData.Values["id"]); if (pluginId < 0) { pluginId = 0; } } catch { } if (pluginId == 0) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true); action = ""; } } Int64 enterpriseId = 0; if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData)) { enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id; } String rData = ""; //SqlConnection //conn = DB.GetConnection(); String jData = ""; try { switch (action) { case "upload_item_template": String id = Request.Form["id"]; String file = Request.Form["file"]; String tSize = Request.Form["size"]; if (String.IsNullOrEmpty(id)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else if (String.IsNullOrEmpty(file)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else if (String.IsNullOrEmpty(tSize)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else { String userHtmlTemplate = "<div id=\"file{0}\" data-id=\"{0}\" data-name=\"{1}\" class=\"app-list-item file-item\">"; userHtmlTemplate += "<div class=\"form-content\"><input type=\"hidden\" name=\"file_name_{0}\" value=\"{1}\">"; userHtmlTemplate += "<input type=\"hidden\" name=\"{1}\" value=\"{0}\"></div>"; userHtmlTemplate += "<table>"; userHtmlTemplate += " <tbody>"; userHtmlTemplate += " <tr>"; userHtmlTemplate += " <td class=\"colfull\">"; userHtmlTemplate += " <div class=\"title\"><span class=\"name\" id=\"file_name_{0}\" data-id=\"{0}\">{1}</span><div class=\"clear-block\"></div></div>"; userHtmlTemplate += " <div class=\"description\">{2}</div></div>"; userHtmlTemplate += " <div class=\"links small\">"; userHtmlTemplate += " <div class=\"last\"><div class=\"ico icon-close\" onclick=\"$('#file{0}').remove();\">Excluir plugin</div></a><div class=\"clear-block\"></div></div>"; userHtmlTemplate += " </div>"; userHtmlTemplate += " </td>"; userHtmlTemplate += " </tr>"; userHtmlTemplate += " </tbody>"; userHtmlTemplate += "</table></div>"; String infoTemplate = "<div class=\"line\">"; infoTemplate += "<label>{1}</label>"; infoTemplate += "<span class=\"no-edit {0}\">{2}</span></div>"; String desc = ""; desc += String.Format(infoTemplate, "status", "Status", "Enviando"); String tHtml = String.Format(userHtmlTemplate, id, file, desc); contentRet = new WebJsonResponse("#" + id, tHtml); } break; case "upload": MultipartFormDataParser mp = new MultipartFormDataParser(Request.InputStream); List <String> fls = new List <String>(); String infoTemplate2 = "<div class=\"line\">"; infoTemplate2 += "<label>{1}</label>"; infoTemplate2 += "<span class=\"no-edit {0}\">{2}</span></div>"; // Loop through all the files foreach (FilePart mpF in mp.Files) { try { String d = ""; DirectoryInfo pluginsDir = null; try { using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection())) pluginsDir = new DirectoryInfo(Path.Combine(c.GetItem("pluginFolder"), "temp\\" + ((EnterpriseData)Page.Session["enterprise_data"]).Id)); if (!pluginsDir.Exists) { pluginsDir.Create(); } } catch { pluginsDir = null; } if (pluginsDir == null) { d += String.Format(infoTemplate2, "", "Status", "Diretório de plugins não encontrado"); } else { try { if (!pluginsDir.Exists) { pluginsDir.Create(); } Byte[] rawAssembly = new Byte[mpF.Data.Length]; mpF.Data.Read(rawAssembly, 0, rawAssembly.Length); List <String> p2 = new List <String>(); List <String> p2Uri = new List <String>(); try { //Realiza teste de compatibilidade com os plugins List <PluginBase> p1 = Plugins.GetPlugins <PluginBase>(rawAssembly); if (p1.Count > 0) { d += String.Format(infoTemplate2, "", "Status", "Arquivo válido"); } else { d += String.Format(infoTemplate2, "", "Status", "Arquivo de plugin inválido"); } foreach (PluginBase p in p1) { p2.Add(p.GetPluginName()); p2Uri.Add(p.GetPluginId().AbsoluteUri); } } catch { d += String.Format(infoTemplate2, "", "Status", "Arquivo de plugin inválido"); } d += String.Format(infoTemplate2, "", "Nome", mpF.FileName); d += String.Format(infoTemplate2, "", "Tamanho", mpF.Data.Length + " bytes"); if (p2.Count > 0) { d += String.Format(infoTemplate2, "", "Plugins", String.Join(", ", p2)); } else { d += String.Format(infoTemplate2, "", "Plugins", "Nenhum plugin encontrado no arquivo enviado"); } if (p2.Count > 0) { using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly in ('" + String.Join("','", p2) + "') or uri in ('" + String.Join("','", p2Uri) + "'))"); if (dt.Rows.Count > 0) { throw new Exception("Plugin/uri ja cadastrado no sistema"); } } FileInfo newFile = new FileInfo(Path.Combine(pluginsDir.FullName, mpF.FileName)); if (newFile.Exists) { newFile.Delete(); } File.WriteAllBytes(newFile.FullName, rawAssembly); } } catch (Exception ex) { d = String.Format(infoTemplate2, "", "Status", "Erro ao realizar o upload"); d += String.Format(infoTemplate2, "", "Informação do erro", ex.Message); } } fls.Add(JSON.Serialize2(new { name = mpF.FileName, html = d })); } catch { fls.Add(JSON.Serialize2(new { name = mpF.FileName, error = "Erro enviando o arquivo" })); } } Retorno.Controls.Add(new LiteralControl("{\"files\": [" + String.Join(",", fls) + "]}")); contentRet = null; break; case "add_new": Dictionary <String, String> files = new Dictionary <string, string>(); foreach (String key in Request.Form.Keys) { if ((key != null) && (key.ToLower().IndexOf("file_name") == 0)) { if (!files.ContainsKey(Request.Form[key].ToLower())) { files.Add(Request.Form[key].ToLower(), Request.Form[Request.Form[key]]); } } } if (files.Count == 0) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true); break; } DirectoryInfo pluginsBase = null; DirectoryInfo pluginsTemp = null; try { using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection())) pluginsBase = new DirectoryInfo(c.GetItem("pluginFolder")); pluginsTemp = new DirectoryInfo(Path.Combine(pluginsBase.FullName, "temp\\" + ((EnterpriseData)Page.Session["enterprise_data"]).Id)); if (!pluginsTemp.Exists) { pluginsTemp.Create(); } } catch { pluginsTemp = null; } if (pluginsTemp == null) { contentRet = new WebJsonResponse("", "Diretório de plugins não encontrado", 3000, true); break; } List <WebJsonResponse> multRet = new List <WebJsonResponse>(); String infoTemplate3 = "<div class=\"line {0}\">"; infoTemplate3 += "<label>{1}</label>"; infoTemplate3 += "<span class=\"no-edit\">{2}</span></div>"; Boolean hasError = false; foreach (String f in files.Keys) { try { FileInfo assemblyFile = new FileInfo(Path.Combine(pluginsTemp.FullName, f)); if (!assemblyFile.Exists) { throw new Exception("Arquivo temporário não encontrado, refaça o upload"); } Byte[] rawAssembly = File.ReadAllBytes(assemblyFile.FullName); List <PluginBase> p1 = Plugins.GetPlugins <PluginBase>(rawAssembly); if (p1.Count == 0) { throw new Exception("Arquivo de plugin inválido"); } foreach (PluginBase p in p1) { using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly = '" + p.GetPluginName() + "' or uri = '" + p.GetPluginId().AbsoluteUri + "')", null); if (dt.Rows.Count > 0) { throw new Exception("Plugin/uri ja cadastrado no sistema"); } } FileInfo newF = new FileInfo(Path.Combine(pluginsBase.FullName, enterpriseId + "-" + assemblyFile.Name)); try { assemblyFile.CopyTo(newF.FullName); DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@name", typeof(String)).Value = p.GetPluginName(); par.Add("@scheme", typeof(String)).Value = p.GetPluginId().Scheme; par.Add("@uri", typeof(String)).Value = p.GetPluginId().AbsoluteUri; par.Add("@assembly", typeof(String)).Value = newF.Name; using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) database.ExecuteNonQuery("INSERT INTO plugin ([enterprise_id],[name],[scheme],[uri],[assembly],[create_date]) VALUES(@enterprise_id, @name, @scheme, @uri, @assembly, getdate())", CommandType.Text, par); try { assemblyFile.Delete(); } catch { } } catch (Exception ex) { try { newF.Delete(); } catch { } throw ex; } } multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .description", String.Format(infoTemplate3, "", "Status", "Plugin inserido com sucesso"))); multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .form-content", "<input type=\"hidden\" />")); } catch (Exception ex) { hasError = true; multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .description", String.Format(infoTemplate3, "error", "Error", ex.Message))); } } if (!hasError) { multRet.Clear(); multRet.Add(new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/plugin/")); } Retorno.Controls.Add(new LiteralControl(JSON.Serialize <List <WebJsonResponse> >(multRet))); contentRet = null; break; case "delete": var reqDel = new { jsonrpc = "1.0", method = "plugin.delete", parameters = new { pluginid = pluginId }, id = 1 }; rData = JSON.Serialize2(reqDel); using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData); if (String.IsNullOrWhiteSpace(jData)) { throw new Exception(""); } RoleDeleteResult retDel = JSON.Deserialize <RoleDeleteResult>(jData); if (retDel == null) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true); } else if (retDel.error != null) { contentRet = new WebJsonResponse("", retDel.error.data, 3000, true); } else if (!retDel.result) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true); } else { contentRet = new WebJsonResponse(); } break; } } catch (Exception ex) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } finally { } if (contentRet != null) { if (!String.IsNullOrWhiteSpace((String)Request["cid"])) { contentRet.callId = (String)Request["cid"]; } Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON())); } }
protected void Page_Load(object sender, EventArgs e) { try { Request.InputStream.Position = 0; JSONRequest req = JSON.GetRequest(Request.InputStream); JsonGeneric data = new JsonGeneric(); data.FromJsonString(req.data); if (data.data.Count == 0) { return; } using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { ProxyConfig config = new ProxyConfig(); config.GetDBConfig(db.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host); if (config.fqdn == null) //Não encontrou o proxy { return; } String uri = Tools.Tool.TrataInjection(data.data[0][data.GetKeyIndex("uri")]); DataTable dt = db.Select("select * from plugin where uri = '" + uri + "'"); if ((dt == null) || (dt.Rows.Count == 0)) { return; } DirectoryInfo pluginsDir = null; using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection())) pluginsDir = new DirectoryInfo(c.GetItem("pluginFolder")); if (pluginsDir == null) { throw new Exception("Parâmtro 'pluginFolder' não encontrado"); } if (pluginsDir.Exists) { FileInfo f = new FileInfo(Path.Combine(pluginsDir.FullName, dt.Rows[0]["assembly"].ToString())); if (f.Exists) { Byte[] fData = File.ReadAllBytes(f.FullName); String fileHash = CATools.SHA1Checksum(fData); Int32 ci = data.GetKeyIndex("checksum"); if ((ci != -1) && (data.data[0][ci] == fileHash)) { ReturnHolder.Controls.Add(new LiteralControl("{ \"name\":\"" + f.Name + "\", \"status\":\"updated\"}")); } else { String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), fData)) ReturnHolder.Controls.Add(new LiteralControl("{ \"name\":\"" + f.Name + "\", \"status\":\"outdated\", \"date\":\"" + f.LastWriteTimeUtc.ToString("yyyy-MM-dd HH:mm:ss") + "\", \"content\":\"" + Convert.ToBase64String(cApi.ToBytes()) + "\"}")); } fData = new Byte[0]; } } /* * ProxyConfig config = new ProxyConfig(); * config.GetDBConfig(IAMDatabase.GetWebConnection(), ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host); * * if (config.fqdn != null) * { * ReturnHolder.Controls.Add(new LiteralControl(config.ToJsonString())); * }*/ } } catch (Exception ex) { Tools.Tool.notifyException(ex); throw ex; } }