//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 { } }
static public void sendEmail(MSSQLDB db, String Subject, List <String> to, String replyTo, String body, Boolean isHTML, List <Attachment> atts) { using (ServerDBConfig conf = new ServerDBConfig(db.conn)) { MailMessage mail = new MailMessage(); mail.From = new MailAddress(conf.GetItem("mailFrom")); foreach (String t in to) { mail.To.Add(new MailAddress(t)); } mail.Subject = Subject; mail.IsBodyHtml = isHTML; mail.Body = body; if (replyTo != null) { try { mail.ReplyTo = new MailAddress(replyTo); } catch { } } if ((atts != null) && (atts.Count > 0)) { foreach (Attachment a in atts) { mail.Attachments.Add(a); } } SmtpClient client = new SmtpClient(); client.Host = conf.GetItem("smtpServer"); client.Port = 587; client.EnableSsl = true; client.Credentials = new System.Net.NetworkCredential(conf.GetItem("username"), conf.GetItem("password")); System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidationCallback); client.Send(mail); client = null; mail = null; } }
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())) using (ServerDBConfig conf = new ServerDBConfig(database.Connection)) { ProxyConfig config = new ProxyConfig(); config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host); if (config.fqdn != null) //Encontrou o proxy { if ((req.data != null) && (req.data != "")) { String dData = req.data; try { dData = Encoding.UTF8.GetString(Convert.FromBase64String(dData)); } catch { } String header = "Proxy: " + req.host + Environment.NewLine; header += "IP: " + Tools.Tool.GetIPAddress() + Environment.NewLine; header += "Data: " + Environment.NewLine + Environment.NewLine; Tools.Tool.sendEmail("Proxy log received from " + req.host + " " + DateTime.Now.ToString("yyyy-MM-dd"), conf.GetItem("to"), header + dData, false); } ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", "Request received with " + (req.data != null ? req.data.Length.ToString() : "0") + " bytes and proxy found"))); } } } catch (Exception ex) { Tools.Tool.notifyException(ex); throw ex; } }
static public void sendEmail(IAMDatabase db, String Subject, List <MailAddress> to, String replyTo, String body, Boolean isHTML, List <Attachment> atts) { using (ServerDBConfig conf = new ServerDBConfig(db.Connection)) { MailMessage mail = new MailMessage(); mail.From = new MailAddress(conf.GetItem("mailFrom")); foreach (MailAddress t in to) { mail.To.Add(t); } mail.Subject = Subject; mail.IsBodyHtml = isHTML; mail.Body = body; if (replyTo != null) { try { mail.ReplyTo = new MailAddress(replyTo); } catch { } } if ((atts != null) && (atts.Count > 0)) { foreach (Attachment a in atts) { mail.Attachments.Add(a); } } /*Non-Encrypted AUTH 25 (or 587) * Secure (TLS) StartTLS 587 * Secure (SSL) SSL 465*/ 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 { } if (!String.IsNullOrEmpty(conf.GetItem("username")) && !String.IsNullOrEmpty(conf.GetItem("password"))) { client.Credentials = new System.Net.NetworkCredential(conf.GetItem("username"), conf.GetItem("password")); } System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidationCallback); client.Send(mail); client = null; mail = null; } }
protected void Page_Load(object sender, EventArgs e) { if (!EnterpriseIdentify.Identify(Page, false, true)) //Se houver falha na identificação da empresa finaliza a resposta { Page.Response.Status = "403 Access denied"; Page.Response.StatusCode = 403; Page.Response.End(); return; } else { String proxyName = ""; String version = ""; Int32 pid = 0; try { proxyName = Request.Headers["X-SAFEID-PROXY"]; } catch { } try { version = Request.Headers["X-SAFEID-VERSION"]; } catch { } try { pid = Int32.Parse(Request.Headers["X-SAFEID-PID"]); } catch { } if (String.IsNullOrEmpty(proxyName)) { Page.Response.Status = "403 Access denied"; Page.Response.StatusCode = 403; Page.Response.End(); return; } Int32 files = 0; Int32 rConfig = 0; Int32 fetch = 0; Boolean restart = false; try { using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) using (ServerDBConfig c = new ServerDBConfig(db.Connection)) { ProxyConfig config = new ProxyConfig(); config.GetDBConfig(db.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, proxyName); if (config.fqdn != null) //Encontrou o proxy { DirectoryInfo outDir = null; outDir = new DirectoryInfo(Path.Combine(c.GetItem("outboundFiles"), config.proxyID + "_" + config.proxy_name)); if (!outDir.Exists) { outDir.Create(); } files = outDir.GetDirectories().Length; if (config.forceDownloadConfig) { rConfig++; } //Verifica fetch try { fetch = db.ExecuteScalar <Int32>("select COUNT(*) from resource_plugin_fetch f with(nolock) inner join resource_plugin rp with(nolock) on rp.id = f.resource_plugin_id inner join resource r with(nolock) on r.id = rp.resource_id where f.response_date is null and proxy_id = " + config.proxyID, System.Data.CommandType.Text, null); } catch { } try { restart = db.ExecuteScalar <Boolean>("select restart from proxy where id = " + config.proxyID, System.Data.CommandType.Text, null); } catch { } try { db.ExecuteNonQuery("update proxy set restart = 0 where id = " + config.proxyID, System.Data.CommandType.Text, null); } catch { restart = false; } db.ExecuteNonQuery("update proxy set last_sync = getdate(), pid = " + pid + ", address = '" + Tools.Tool.GetIPAddress() + "', config = 0, version = '" + version + "' where id = " + config.proxyID, System.Data.CommandType.Text, null); } else { db.AddUserLog(LogKey.API_Error, DateTime.Now, "ProxyAPI", UserLogLevel.Warning, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "Proxy not found " + proxyName); Page.Response.Status = "403 Access denied"; Page.Response.StatusCode = 403; return; } } } catch (Exception ex) { Tools.Tool.notifyException(ex, this); //throw ex; } Page.Response.HeaderEncoding = Encoding.UTF8; ReturnHolder.Controls.Add(new LiteralControl("{\"config\":" + rConfig + ",\"files\":" + files + ",\"fetch\":" + fetch + ",\"restart\":" + (restart ? "1" : "0") + "}")); } }
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 { } }
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) { 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; } }
private void MessengerTimer(Object state) { if (executing) { return; } executing = true; startTime = DateTime.Now; try { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 900; //Lista todas as mensagens pendêntes de entrega //Status: W = Waiting, PE = Protocol error //DataTable dtMessages = db.ExecuteDataTable("select m.*, e.last_uri from [st_messages] m with(nolock) inner join enterprise e with(nolock) on e.id = m.enterprise_id where status in ('W','PE')"); DataTable dtMessages = db.ExecuteDataTable("select m.id from [st_messages] m with(nolock) where status in ('W','PE')"); if ((dtMessages != null) && (dtMessages.Rows.Count > 0)) { try { TextLog.Log("Messenger", "Starting message timer"); foreach (DataRow dr in dtMessages.Rows) { try { using (MessageSender sender = new MessageSender(db, (Int64)dr["id"])) using (ServerDBConfig conf = new ServerDBConfig(db.Connection, true)) sender.Send(conf.GetItem("mailFrom"), conf.GetItem("smtpServer"), conf.GetItem("username"), conf.GetItem("password")); } catch (Exception ex) { DbParameterCollection par = new DbParameterCollection(); par.Add("@message_id", typeof(Int64)).Value = (Int64)dr["id"]; par.Add("@status", typeof(String)).Value = "Erro no envio"; par.Add("@description", typeof(String)).Value = ex.Message; db.ExecuteNonQuery("UPDATE st_messages SET [status] = 'E' WHERE id = @message_id; INSERT INTO st_messages_status (message_id,date,error,status,description) VALUES(@message_id,getdate(),1,@status,@description);", par); } } } finally { if (db != null) { db.Dispose(); } TextLog.Log("Messenger", "Finishing message timer"); } } db.closeDB(); } finally { if (db != null) { db.Dispose(); } } } catch (Exception ex) { TextLog.Log("Messenger", "Error on message timer " + ex.Message); } finally { executing = false; last_status = ""; startTime = new DateTime(1970, 1, 1); } }
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) { 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())); } }
public override LoginResult Auth(IAMDatabase database, System.Web.UI.Page page) { Dictionary <String, Object> config = GetAuthConfig(database, page); if (!CheckInputConfig(config, Log)) { return(new LoginResult(false, "Invalid config")); } String cas_service = config["uri"].ToString(); String ticket = (!String.IsNullOrEmpty(page.Request.QueryString["ticket"]) ? page.Request.QueryString["ticket"].ToString() : ""); String service = HttpUtility.UrlEncode(page.Request.Url.Scheme + "://" + page.Request.Url.Host + (page.Request.Url.Port != 80 ? ":" + page.Request.Url.Port : "") + "/login/"); //String tst = page.Request.Url.AbsoluteUri; if (ticket != "") { page.Session["login"] = null; //Verifica o ticket using (ServerDBConfig conf = new ServerDBConfig(database.Connection, true)) { String result = null; try { WebClient client = new WebClient(); Uri req = new Uri(cas_service.TrimEnd("/".ToCharArray()) + "/serviceValidate/?service=" + service + "&ticket=" + ticket); result = client.DownloadString(req); } catch { } if (!String.IsNullOrEmpty(result)) { XmlDocument doc = new XmlDocument(); doc.LoadXml("<?xml version=\"1.0\"?>" + result); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("cas", "http://www.yale.edu/tp/cas"); XmlNode failNode = doc.SelectSingleNode("/cas:serviceResponse/cas:authenticationFailure", namespaceManager); XmlNode successNode = doc.SelectSingleNode("/cas:serviceResponse/cas:authenticationSuccess", namespaceManager); if ((failNode == null) && (successNode != null)) { XmlNode user = doc.SelectSingleNode("/cas:serviceResponse/cas:authenticationSuccess/cas:user", namespaceManager); LoginResult login = LocalAuth(database, page, user.ChildNodes[0].Value, "", true); if (login.Success) { if (page.Session["last_page"] != null) { page.Response.Redirect(page.Session["last_page"].ToString(), false); page.Session["last_page"] = null; } else { page.Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "autoservice/", false); } } else { page.Response.Redirect(cas_service.TrimEnd("/".ToCharArray()) + "/login/?renew=true&service=" + service, false); } return(login); } else { page.Response.Redirect(cas_service.TrimEnd("/".ToCharArray()) + "/login/?renew=true&service=" + service, false); return(new LoginResult(false, "XML Error")); } } else { page.Response.Redirect(cas_service.TrimEnd("/".ToCharArray()) + "/login/?renew=true&service=" + service, false); return(new LoginResult(false, "CAS Result is empry")); } } } else { page.Response.Redirect(cas_service.TrimEnd("/".ToCharArray()) + "/login/?service=" + service, false); return(new LoginResult(false, "Ticket is empty")); } }
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; } }