private void SaveToSend(JsonGeneric data, String prefix) { if ((data.data == null) || (data.data.Count == 0)) { return; } Byte[] jData = data.ToJsonBytes(); using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.server_cert)), jData)) { DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(basePath, "Out")); if (!dirTo.Exists) { dirTo.Create(); } FileInfo f = new FileInfo(Path.Combine(dirTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff") + "-" + prefix) + ".iamdat"); File.WriteAllBytes(f.FullName, cApi.ToBytes()); TextLog.Log("PluginStarter", "File to send created " + f.Name + " (" + data.data.Count + ")"); data.data.Clear(); } }
private static void ParseModifierBin() { using (StreamReader rdr = new StreamReader(CryptApi.DecryptStream(GetStream(), CryptApi.NoxCryptFormat.MODIFIER))) { string type = ""; while (rdr.BaseStream.Position < rdr.BaseStream.Length) { string line = rdr.ReadLine().Trim(); if (line == "") { continue; } if (line == "END") { type = ""; continue; } if (line == "WEAPON_DEFINITIONS" || line == "ARMOR_DEFINITIONS" || line == "EFFECTIVENESS" || line == "MATERIAL" || line == "ENCHANTMENT") { type = line; continue; } Mods.Add(line, new Mod(rdr, line, type)); } } }
private void SaveToSend(Int64 enterpriseId, DirectoryInfo saveTo, ProxyConfig config, List <PluginConnectorBaseDeployPackage> packages) { if ((packages == null) || (packages.Count == 0)) { return; } Byte[] jData = Encoding.UTF8.GetBytes(SafeTrend.Json.JSON.Serialize <List <PluginConnectorBaseDeployPackage> >(packages)); String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), jData)) { if (!saveTo.Exists) { saveTo.Create(); } FileInfo f = new FileInfo(Path.Combine(saveTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff")) + ".iamdat"); File.WriteAllBytes(f.FullName, cApi.ToBytes()); foreach (PluginConnectorBaseDeployPackage pkg in packages) { try { //db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Debug, 0, enterpriseId, 0, 0, 0, pkg.entityId, pkg.identityId, "Saving package ID: " + pkg.pkgId, SafeTrend.Json.JSON.Serialize<PluginConnectorBaseDeployPackage>(pkg)); String tpkg = SafeTrend.Json.JSON.Serialize <PluginConnectorBaseDeployPackage>(pkg); DbParameterCollection par = new DbParameterCollection(); par.Add("@entity_id", typeof(Int64)).Value = pkg.entityId; par.Add("@date", typeof(DateTime)).Value = DateTime.Now; par.Add("@flow", typeof(String)).Value = "deploy"; par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId; par.Add("@filename", typeof(String), f.FullName.Length).Value = f.FullName; par.Add("@package", typeof(String), tpkg.Length).Value = tpkg; Int64 trackId = db.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null); tpkg = null; db.AddPackageTrack(trackId, "deploy", "Package generated"); } catch { } } #if DEBUG db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, 0, 0, "File to send created " + f.Name + " (" + packages.Count + ")"); #endif } }
public void SaveToSend(String sufix) { if ((logRecords1.data != null) && (logRecords1.data.Count > 0)) { Byte[] jData = logRecords1.ToJsonBytes(); using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(this.serverCert)), jData)) { DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(this.basePath, "Out")); if (!dirTo.Exists) { dirTo.Create(); } FileInfo f = new FileInfo(Path.Combine(dirTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff") + "-" + sufix) + ".iamdat"); File.WriteAllBytes(f.FullName, cApi.ToBytes()); #if debug TextLog.Log("PluginStarter", "File to send created " + f.Name + " (" + logRecords.data.Count + ")"); #endif logRecords1.data.Clear(); } } if ((logRecords2.data != null) && (logRecords2.data.Count > 0)) { Byte[] jData = logRecords2.ToJsonBytes(); using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(this.serverCert)), jData)) { DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(this.basePath, "Out")); if (!dirTo.Exists) { dirTo.Create(); } FileInfo f = new FileInfo(Path.Combine(dirTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff") + "-pl-" + sufix) + ".iamdat"); File.WriteAllBytes(f.FullName, cApi.ToBytes()); #if debug TextLog.Log("PluginStarter", "File to send created " + f.Name + " (" + logRecords.data.Count + ")"); #endif logRecords2.data.Clear(); } } }
private List <PluginConnectorBaseDeployPackage> LoadFile(FileInfo file) { Byte[] fData = File.ReadAllBytes(file.FullName); String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); try { using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), fData)) { List <PluginConnectorBaseDeployPackage> data = null; data = JSON.Deserialize <List <PluginConnectorBaseDeployPackage> >(Encoding.UTF8.GetString(cApi.clearData)); return(data); } } finally { certPass = null; fData = new Byte[0]; } }
public override void Close() { //encrypt before closing SkipToNextBoundary(); //pad so total length is divisible by 8 int length = (int)BaseStream.Position; byte[] buffer = new byte[length]; BaseStream.Seek(0, SeekOrigin.Begin); BaseStream.Read(buffer, 0, length); if (format != CryptApi.NoxCryptFormat.NONE) { buffer = CryptApi.NoxEncrypt(buffer, format); } BaseStream.Seek(0, SeekOrigin.Begin); Write(buffer); base.Close(); }
public Byte[] ToBytes() { Byte[] jData = new Byte[0]; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List <PluginConnectorBaseFetchPackage>)); using (MemoryStream ms = new MemoryStream()) { ser.WriteObject(ms, this.fetch_packages); ms.Flush(); jData = ms.ToArray(); } Byte[] retData = new Byte[0]; String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(fqdn)); using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(client_cert), certPass), jData)) { retData = cApi.ToBytes(); } return(retData); }
public static void BuildPassword(MSSQLDB db, SqlTransaction trans, Int64 context, Int64 entityId, Int64 enterpriseId) { String pwdMethod = "random"; String pwdValue = ""; using (DataTable dtRules = db.Select("select password_rule from context c where c.id = " + context + " and (c.password_rule is not null and rtrim(LTRIM(c.password_rule)) <> '')", trans)) { if ((dtRules != null) && (dtRules.Rows.Count > 0)) { String v = dtRules.Rows[0]["password_rule"].ToString().Trim(); if (v.IndexOf("[") != -1) { Regex rex = new Regex(@"(.*?)\[(.*?)\]"); Match m = rex.Match(v); if (m.Success) { pwdMethod = m.Groups[1].Value.ToLower(); pwdValue = m.Groups[2].Value; } } else { pwdMethod = v; } } } switch (pwdMethod) { case "default": //Nada a senha ja foi definida break; case "field": throw new NotImplementedException(); /* * Int64 fieldId = 0; * Int64.TryParse(pwdValue, out fieldId); * using (DataTable dtFields = db.Select("select * from identity_field where identity_id = " + this.IdentityId + " and field_id = " + fieldId, trans)) * if ((dtFields != null) && (dtFields.Rows.Count > 0)) * { * pwdValue = dtFields.Rows[0]["value"].ToString(); * }*/ break; default: //Random pwdValue = ""; break; } //Se a senha continua vazia, gera uma randômica if ((pwdValue == null) || (pwdValue == "")) { pwdValue = RandomPassword.Generate(14, 16); } Boolean MustChangePassword = true; String pwd = ""; using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.conn, enterpriseId, trans)) using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(pwdValue))) pwd = Convert.ToBase64String(cApi.ToBytes()); String sql = "update entity set password = @password, change_password = getdate(), must_change_password = @must where id = @entityId"; SqlParameterCollection par = GetSqlParameterObject(); par.Add("@entityId", SqlDbType.BigInt).Value = entityId; par.Add("@password", SqlDbType.VarChar, pwd.Length).Value = pwd; par.Add("@must", SqlDbType.Bit).Value = MustChangePassword; db.AddUserLog(LogKey.User_PasswordChanged, null, "Engine", UserLogLevel.Info, 0, 0, context, 0, 0, entityId, 0, "Password changed", "", trans); db.ExecuteNonQuery(sql, CommandType.Text, par, trans); }
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 { } }
private void InboundTimer(Object state) { TextLog.Log("Server", "Starting inbound timer"); try { DirectoryInfo inDir = new DirectoryInfo(Path.Combine(basePath, "In")); if (!inDir.Exists) { TextLog.Log("Server", "\t0 files to process"); return; } FileInfo[] files = inDir.GetFiles("*.iamreq"); TextLog.Log("Server", "\t" + files.Length + " files to process"); MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); foreach (FileInfo f in files) { JSONRequest req = null; try { using (FileStream fs = f.OpenRead()) req = JSON.GetRequest(fs); if ((req.host == null) || (req.host == "")) { TextLog.Log("Server", "Paramter 'host' is empty on " + f.Name); continue; } if ((req.enterpriseid == null) || (req.enterpriseid == "")) { TextLog.Log("Server", "Paramter 'enterpriseid' is empty on " + f.Name); continue; } try { Int64 tst = Int64.Parse(req.enterpriseid); } catch { if ((req.enterpriseid == null) || (req.enterpriseid == "")) { TextLog.Log("Server", "Paramter 'enterpriseid' is not Int64 " + f.Name); continue; } } ProxyConfig config = new ProxyConfig(true); config.GetDBCertConfig(db.conn, Int64.Parse(req.enterpriseid), req.host); if (config.fqdn != null) //Encontrou o proxy { JsonGeneric jData = new JsonGeneric(); try { String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), Convert.FromBase64String(req.data))) jData.FromJsonBytes(cApi.clearData); } catch (Exception ex) { jData = null; TextLog.Log("Server", "Error on decrypt package data " + f.Name + " for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message); } if (jData == null) { continue; } Int32 contextCol = jData.GetKeyIndex("context"); Int32 uriCol = jData.GetKeyIndex("uri"); Int32 importidCol = jData.GetKeyIndex("importid"); Int32 registryidCol = jData.GetKeyIndex("registryid"); Int32 datanameCol = jData.GetKeyIndex("dataname"); Int32 datavalueCol = jData.GetKeyIndex("datavalue"); Int32 datatypeCol = jData.GetKeyIndex("datatype"); if (uriCol == -1) { TextLog.Log("Server", "Erro on find column 'uri' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (importidCol == -1) { TextLog.Log("Server", "Erro on find column 'importid' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (registryidCol == -1) { TextLog.Log("Server", "Erro on find column 'registryid' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (datanameCol == -1) { TextLog.Log("Server", "Erro on find column 'dataname' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (datavalueCol == -1) { TextLog.Log("Server", "Erro on find column 'datavalue' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (datatypeCol == -1) { TextLog.Log("Server", "Erro on find column 'datatype' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } DateTime date = DateTime.Now; //Realiza a importação no modelo BulkInsert por melhor desempenho do banco DataTable dtBulk = new DataTable(); dtBulk.Columns.Add(new DataColumn("date", typeof(DateTime))); dtBulk.Columns.Add(new DataColumn("plugin_uri", typeof(String))); dtBulk.Columns.Add(new DataColumn("context_id", typeof(Int64))); dtBulk.Columns.Add(new DataColumn("import_id", typeof(String))); dtBulk.Columns.Add(new DataColumn("registry_id", typeof(String))); dtBulk.Columns.Add(new DataColumn("data_name", typeof(String))); dtBulk.Columns.Add(new DataColumn("data_value", typeof(String))); dtBulk.Columns.Add(new DataColumn("data_type", typeof(String))); foreach (String[] dr in jData.data) { dtBulk.Rows.Add(new Object[] { date, dr[uriCol], Int64.Parse(dr[contextCol]), dr[importidCol], dr[registryidCol], dr[datanameCol], dr[datavalueCol], dr[datatypeCol] }); } db.BulkCopy(dtBulk, "collector_imports"); TextLog.Log("Server", "Imported " + dtBulk.Rows.Count + " registers for enterprise " + req.enterpriseid + " and proxy " + req.host); dtBulk.Dispose(); dtBulk = null; jData = null; f.Delete(); } else { TextLog.Log("Server", "Proxy config not found for enterprise " + req.enterpriseid + " and proxy " + req.host); } config = null; } finally { req = null; } } db.closeDB(); } catch (Exception ex) { TextLog.Log("Server", "Error on inbound timer " + ex.Message); } finally { TextLog.Log("Server", "Finishing inbound timer"); } }
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; } }
static void ExecuteConnector(Boolean deployOnly) { List <Int64> resource = new List <Int64>(); //Separa os contextos String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); OpenSSL.X509.X509Certificate cert = CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass); foreach (PluginConfig p in config.plugins) { if (p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower()) { JsonGeneric pgConf = new JsonGeneric(); try { using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters))) pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData)); } catch (Exception ex) { throw new Exception("Decrypt error1 " + ex.Message); } finally { pgConf = null; } if (!resource.Contains(p.resource)) { resource.Add(p.resource); } } } foreach (Int64 r in resource) { Dictionary <String, Object> connectorConf = new Dictionary <String, Object>(); Dictionary <String, String> mapping = new Dictionary <String, String>(); Boolean enableDeploy = false; try { foreach (PluginConfig p in config.plugins) { if ((p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower()) && (p.resource == r)) { mapping = p.mappingDataTypeDic; enableDeploy = p.enable_deploy; JsonGeneric pgConf = new JsonGeneric(); try { if (cert == null) { throw new Exception("Certificate is null"); } using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters))) pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData)); } catch (Exception ex) { throw new Exception("Decrypt error: " + ex.Message); } if ((pgConf.data == null) || (pgConf.data.Count == 0)) { continue; } Int32 kCol = pgConf.GetKeyIndex("key"); Int32 vCol = pgConf.GetKeyIndex("value"); if (!String.IsNullOrWhiteSpace(p.mail_domain)) { connectorConf.Add("iam_mail_domain", p.mail_domain); } foreach (String[] d1 in pgConf.data) { if (!connectorConf.ContainsKey(d1[kCol])) { connectorConf.Add(d1[kCol], d1[vCol].ToString()); } } } } //Deploy ocorre antes da importação //Para que na importação ja apareça os registros que foram publicados pelo deploy try { if (enableDeploy) { ProcessDeploy(r, connectorConf, mapping); } else { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Deploy disabled"); //Exclui os arquivos System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(plugin.GetType()); DirectoryInfo dirFrom = new DirectoryInfo(Path.Combine(basePath, "In\\" + Path.GetFileNameWithoutExtension(asm.Location) + "\\" + resource)); if (dirFrom.Exists) { foreach (FileInfo f in dirFrom.GetFiles("*.iamdat")) { f.Delete(); } } } } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on deploy: " + ex.Message); } if (!deployOnly) { try { //O import não é desabilitado, pois ele é necessário para relatório de consistência //o Engine não utilizará ele para adicionar novas entidades ProcessImport(r, connectorConf, mapping); } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on import: " + ex.Message); } } } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on parse config: " + ex.Message); } finally { connectorConf.Clear(); connectorConf = null; mapping.Clear(); mapping = null; } } cert = null; certPass = null; }
protected void Page_Load(object sender, EventArgs e) { WebJsonResponse ret = null; try { Int64 enterpriseID = ((EnterpriseData)Page.Session["enterprise_data"]).Id; Int64 entityId = 0; String err = ""; String password = Tools.Tool.TrataInjection(Request["password"]); String password2 = Request["password2"]; 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 { 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 code = ""; if (Session["entityId"] != null) { entityId = (Int64)Session["entityId"]; } if (Session["userCode"] != null) { code = Session["userCode"].ToString(); } if ((entityId > 0) && (code != "")) { using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { UserPasswordStrength usrCheck = new UserPasswordStrength(db.Connection, entityId); 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 = " + entityId + " and recovery_code = '" + code + "'"); if ((c != null) && (c.Rows.Count > 0)) { using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId)) using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password))) db.ExecuteNonQuery("update entity set password = '******', recovery_code = null, last_login = getdate(), change_password = getdate(), must_change_password = 0 where id = " + entityId, CommandType.Text, null); db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, entityId, 0, "Password changed through recovery code", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} "); //Cria o pacote com os dados atualizados deste usuário //Este processo vija agiliar a aplicação das informações pelos plugins db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + entityId + ")", CommandType.Text, null); String html = ""; html += "<div class=\"login_form\">"; html += "<ul>"; html += " <li class=\"title\">"; html += " <strong>" + MessageResource.GetMessage("password_changed_sucessfully") + "</strong>"; html += " </li>"; html += " <li>"; html += " <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("password_changed_text") + "</p>"; html += " </li>"; html += " <li>"; html += " <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("return_default") + "</a></span>"; html += " </li>"; html += "</ul> "; html += "</div>"; ret = new WebJsonResponse("#recover_container", html); } else { ret = new WebJsonResponse("", MessageResource.GetMessage("invalid_code"), 3000, true); } } } } else { ret = new WebJsonResponse("", MessageResource.GetMessage("invalid_session"), 3000, true); } } } catch (Exception ex) { Tools.Tool.notifyException(ex); throw ex; } if (ret != null) { ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON())); } }
public PluginConfig(OpenSSL.X509.X509Certificate cert, SqlConnection conn, String scheme, Int64 pluginId, Int64 resourcePluginId) { this.Connection = conn; switch (scheme.ToLower()) { case "connector": DataTable dt = ExecuteDataTable("select p.id plugin_id, p.uri, p.[assembly], rp.*, rp.id resource_plugin_id from plugin p with(nolock) inner join resource_plugin rp with(nolock) on rp.plugin_id = p.id inner join [resource] r with(nolock) on r.id = rp.resource_id where r.enabled = 1 and rp.enabled = 1 and rp.id = " + resourcePluginId); if ((dt != null) && (dt.Rows.Count > 0)) { DataRow dr = dt.Rows[0]; DataTable dt2 = ExecuteDataTable("select top 1 schedule from resource_plugin_schedule with(nolock) where resource_plugin_id = " + dr["resource_plugin_id"].ToString()); if ((dt2 != null) && (dt2.Rows.Count > 0)) { this.schedule = dt2.Rows[0]["schedule"].ToString(); } this.mapping = new List <PluginConfigMapping>(); //Adiciona os mapeamentos padrões (login, e-mail e nome), se estiver mapeado DataTable dt3 = ExecuteDataTable("select rp.id resource_plugin_id, f.id field_id, f.name field_name, 'login' data_name, f.data_type, cast(0 as bit) is_password, cast(0 as bit) is_property, cast(0 as bit) is_id, is_unique_property = case when f.id = rp.login_field_id then cast(1 as bit) else cast(0 as bit) end from resource_plugin rp with(nolock) inner join field f with(nolock) on rp.login_field_id = f.id where rp.id = " + dr["resource_plugin_id"].ToString()); if ((dt3 != null) && (dt3.Rows.Count > 0)) { foreach (DataRow dr3 in dt3.Rows) { this.mapping.Add(new PluginConfigMapping( (Int64)dr3["field_id"], dr3["field_name"].ToString(), dr3["data_name"].ToString(), dr3["data_type"].ToString(), (Boolean)dr3["is_id"], (Boolean)dr3["is_password"], (Boolean)dr3["is_property"], (Boolean)dr3["is_unique_property"], ((Int64)dr["login_field_id"] == (Int64)dr3["field_id"]), ((Int64)dr["name_field_id"] == (Int64)dr3["field_id"]) )); } } //Adiciona os mapeamentos DataTable dt4 = ExecuteDataTable("select m.*, f.data_type, f.name field_name from resource_plugin_mapping m with(nolock) inner join resource_plugin rp with(nolock) on rp.id = m.resource_plugin_id inner join field f with(nolock) on m.field_id = f.id where rp.id = " + dr["resource_plugin_id"].ToString()); if ((dt4 != null) && (dt4.Rows.Count > 0)) { foreach (DataRow dr4 in dt4.Rows) { this.mapping.Add(new PluginConfigMapping( (Int64)dr4["field_id"], dr4["field_name"].ToString(), dr4["data_name"].ToString(), dr4["data_type"].ToString(), (Boolean)dr4["is_id"], (Boolean)dr4["is_password"], (Boolean)dr4["is_property"], (Boolean)dr4["is_unique_property"], ((Int64)dr["login_field_id"] == (Int64)dr4["field_id"]), ((Int64)dr["name_field_id"] == (Int64)dr4["field_id"]) )); } } //Adiciona o campo de login caso não exista DataTable dt5 = ExecuteDataTable("select rp.id resource_plugin_id, f.id field_id, f.name field_name, 'login' data_name, f.data_type, cast(0 as bit), cast(0 as bit), cast(0 as bit) is_id, is_unique_property = case when f.id = rp.login_field_id then cast(1 as bit) else cast(0 as bit) end from resource_plugin rp with(nolock) inner join field f with(nolock) on rp.login_field_id = f.id where rp.id = " + dr["resource_plugin_id"].ToString()); if ((dt5 != null) && (dt5.Rows.Count > 0)) { foreach (DataRow dr5 in dt5.Rows) { if (!this.mapping.Exists(m => (m.is_login))) { this.mapping.Add(new PluginConfigMapping( (Int64)dr5["field_id"], dr5["field_name"].ToString(), dr5["data_name"].ToString(), dr5["data_type"].ToString(), (Boolean)dr5["is_id"], (Boolean)dr5["is_password"], (Boolean)dr5["is_property"], (Boolean)dr5["is_unique_property"], ((Int64)dr["login_field_id"] == (Int64)dr5["field_id"]), ((Int64)dr["name_field_id"] == (Int64)dr5["field_id"]) )); } } } this.uri = dr["uri"].ToString(); this.assembly = dr["assembly"].ToString(); this.resource = (Int64)dr["resource_id"]; this.resource_plugin = (Int64)dr["id"]; this.name_field_id = (Int64)dr["name_field_id"]; this.mail_field_id = (Int64)dr["mail_field_id"]; this.login_field_id = (Int64)dr["login_field_id"]; this.enable_import = (Boolean)dr["enable_import"]; this.enable_deploy = (Boolean)dr["enable_deploy"]; this.import_groups = (Boolean)dr["import_groups"]; this.import_containers = (Boolean)dr["import_containers"]; this.permit_add_entity = (Boolean)dr["permit_add_entity"]; this.mail_domain = dr["mail_domain"].ToString(); this.build_login = (Boolean)dr["build_login"]; this.build_mail = (Boolean)dr["build_mail"]; this.order = (Int32)dr["order"]; this.plugin_id = (Int64)dr["plugin_id"]; if (cert != null) { JsonGeneric cfg = new JsonGeneric(); cfg.fields = new String[] { "key", "value" }; DataTable dt1 = ExecuteDataTable("select [key], [value] from resource_plugin_par with(nolock) where resource_plugin_id = " + dr["resource_plugin_id"].ToString()); if ((dt1 != null) && (dt1.Rows.Count > 0)) { foreach (DataRow dr1 in dt1.Rows) { cfg.data.Add(new String[] { dr1["key"].ToString(), dr1["value"].ToString() }); } } using (CryptApi cApi = new CryptApi(cert, Encoding.UTF8.GetBytes(cfg.ToJsonString()))) parameters = Convert.ToBase64String(cApi.ToBytes()); } } break; case "agent": DataTable dtA = ExecuteDataTable("select p.id plugin_id, p.uri, p.[assembly], pp.id proxy_plugin_id from plugin p with(nolock) inner join proxy_plugin pp with(nolock) on pp.plugin_id = p.id where pp.enabled = 1 and p.id = " + pluginId); if ((dtA != null) && (dtA.Rows.Count > 0)) { DataRow dr = dtA.Rows[0]; this.uri = dr["uri"].ToString(); this.assembly = dr["assembly"].ToString(); this.plugin_id = (Int64)dr["plugin_id"]; if (cert != null) { JsonGeneric cfg = new JsonGeneric(); cfg.fields = new String[] { "key", "value" }; DataTable dt1 = ExecuteDataTable("select [key], [value] from proxy_plugin_par with(nolock) where proxy_plugin_id = " + dr["proxy_plugin_id"].ToString()); if ((dt1 != null) && (dt1.Rows.Count > 0)) { foreach (DataRow dr1 in dt1.Rows) { cfg.data.Add(new String[] { dr1["key"].ToString(), dr1["value"].ToString() }); } } using (CryptApi cApi = new CryptApi(cert, Encoding.UTF8.GetBytes(cfg.ToJsonString()))) parameters = Convert.ToBase64String(cApi.ToBytes()); } } break; } }
//public static PluginConnectorBaseDeployPackage GetPackage(IAMDatabase db, Int64 proxyId, Int64 resourceId, Int64 pluginId, Int64 entityId, Int64 identityId, Boolean passwordAfterLogin, DateTime? lastChangePassword, String deploy_password_hash) public static PluginConnectorBaseDeployPackage GetPackage(IAMDatabase db, Int64 proxyId, Int64 resourcePluginId, Int64 entityId, Int64 identityId, Boolean passwordAfterLogin, DateTime?lastChangePassword, String deploy_password_hash, Boolean useSalt, Boolean saltOnEnd, String salt) { PluginConnectorBaseDeployPackage pkg = new PluginConnectorBaseDeployPackage(); List <String> deployInfo = new List <string>();//"Identity addedd in deploy package with "; String deployText = ""; deployText = "Package ID: " + pkg.pkgId + Environment.NewLine; try { String sql = "select e.*, c.enterprise_id, rp.plugin_id, i.id identity_id, i.temp_locked, c.name context_name, e1.name enterprise_name, block_inheritance = case when exists (select 1 from identity_block_inheritance bi with(nolock) where bi.identity_id = i.id) then cast(1 as bit) else cast(0 as bit) end from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join resource_plugin rp with(nolock) on rp.id = i.resource_plugin_id inner join enterprise e1 with(nolock) on c.enterprise_id = e1.id where e.id = " + entityId + " and i.id = " + identityId; if (identityId == 0) { sql = "select e.*, c.enterprise_id, rp.plugin_id, cast(0 as bigint) identity_id, cast(0 as bit) as temp_locked, c.name context_name, e1.name enterprise_name, cast(0 as bit) as block_inheritance from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id cross join resource_plugin rp with(nolock) inner join enterprise e1 with(nolock) on c.enterprise_id = e1.id where e.id = " + entityId; } DataTable dtEnt = db.Select(sql); if ((dtEnt == null) || (dtEnt.Rows.Count == 0)) { throw new Exception("Entity/Identity not found"); } //DataTable dtPlugin = db.Select("select p.* from plugin p where p.id = " + pluginId); DataTable dtPlugin = db.Select("select distinct p.*, rp.resource_id from plugin p inner join resource_plugin rp on rp.plugin_id = p.id inner join resource r on rp.resource_id = r.id inner join entity e on e.context_id = r.context_id where rp.id = " + resourcePluginId + " and e.id = " + entityId); if ((dtPlugin == null) || (dtPlugin.Rows.Count == 0)) { throw new Exception("Plugin not found or not linked in the same context of entity"); } if ((Boolean)dtEnt.Rows[0]["block_inheritance"]) { throw new Exception("Inheritance blocked"); } Int64 resourceId = (Int64)dtPlugin.Rows[0]["resource_id"]; Int64 pluginId = (Int64)dtPlugin.Rows[0]["id"]; //Define as pripriedades gerais pkg.registryId = dtEnt.Rows[0]["id"] + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"); pkg.entityId = entityId; pkg.identityId = identityId; pkg.fullName = new FullName(dtEnt.Rows[0]["full_name"].ToString()); pkg.login = dtEnt.Rows[0]["login"].ToString(); pkg.lastChangePassword = (lastChangePassword.HasValue ? lastChangePassword.Value.ToString("o") : null); pkg.locked = (Boolean)dtEnt.Rows[0]["locked"]; pkg.temp_locked = (Boolean)dtEnt.Rows[0]["temp_locked"]; pkg.mustChangePassword = (Boolean)dtEnt.Rows[0]["must_change_password"]; pkg.deleted = (Boolean)dtEnt.Rows[0]["deleted"]; pkg.enterprise = dtEnt.Rows[0]["enterprise_name"].ToString(); pkg.context = dtEnt.Rows[0]["context_name"].ToString(); if ((Boolean)dtEnt.Rows[0]["deleted"]) { db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Deploy to delete identity"); } //Container pkg.container = ""; try { DataTable dtUserContainer = db.Select("select top 1 c.* from [container] c with(nolock) inner join entity_container ec with(nolock) on c.id = ec.container_id where ec.entity_id = " + entityId); if ((dtUserContainer != null) && (dtUserContainer.Rows.Count > 0)) { List <String> path = new List <string>(); path.Add(dtUserContainer.Rows[0]["name"].ToString()); if ((Int64)dtUserContainer.Rows[0]["parent_id"] > 0) { DataTable dtContainers = db.Select("select c.* from container c with(nolock)"); if ((dtContainers != null) || (dtContainers.Rows.Count > 0)) { Func <Int64, Boolean> chields = null; chields = new Func <Int64, Boolean>(delegate(Int64 root) { foreach (DataRow dr in dtContainers.Rows) { if (((Int64)dr["id"] == root)) { path.Add(dr["name"].ToString()); chields((Int64)dr["parent_id"]); break; } } return(true); }); chields((Int64)dtUserContainer.Rows[0]["parent_id"]); } } path.Reverse(); pkg.container = "\\" + String.Join("\\", path); } } catch { } //Senha pkg.password = ""; if ((dtEnt.Rows[0]["password"] != DBNull.Value) && (dtEnt.Rows[0]["password"].ToString().Trim() != "")) { //Este recurso x plugin só permite o deploy da SENHA após o primeiro login if ((!passwordAfterLogin) || ((passwordAfterLogin) && (dtEnt.Rows[0]["last_login"] != DBNull.Value))) { try { String pwd = ""; using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)dtEnt.Rows[0]["enterprise_id"])) using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dtEnt.Rows[0]["password"].ToString()))) pwd = Encoding.UTF8.GetString(cApi.clearData); //Verifica se usará SALT if (useSalt) { if (!String.IsNullOrWhiteSpace(salt)) { if (saltOnEnd) { deployInfo.Add("password + SALT"); pwd = pwd + salt.Trim(); } else { deployInfo.Add("SALT + password"); pwd = salt.Trim() + pwd; } } else { deployInfo.Add("salt is empty"); } } else { deployInfo.Add("no salt"); } if (!String.IsNullOrEmpty(deploy_password_hash)) { switch (deploy_password_hash.ToLower()) { case "md5": using (MD5 hAlg = MD5.Create()) pkg.password = ComputeHash(hAlg, pwd).ToUpper(); pkg.hash_alg = HashAlg.MD5; deployInfo.Add("MD5 password"); break; case "sha1": using (SHA1 hAlg = SHA1.Create()) pkg.password = ComputeHash(hAlg, pwd).ToUpper(); pkg.hash_alg = HashAlg.SHA1; deployInfo.Add("SHA1 password"); break; case "sha256": using (SHA256 hAlg = SHA256.Create()) pkg.password = ComputeHash(hAlg, pwd).ToUpper(); pkg.hash_alg = HashAlg.SHA256; deployInfo.Add("SHA256 password"); break; case "sha512": using (SHA512 hAlg = SHA512.Create()) pkg.password = ComputeHash(hAlg, pwd).ToUpper(); pkg.hash_alg = HashAlg.SHA512; deployInfo.Add("SHA512 password"); break; default: //Nenhum algoritmo de hash pkg.password = pwd; pkg.hash_alg = HashAlg.None; deployInfo.Add("clear text password"); break; } } else { pkg.password = pwd; pkg.hash_alg = HashAlg.None; deployInfo.Add("clear text password"); } deployText += "User password added in deploy" + Environment.NewLine; //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password added in deploy"); } catch (Exception ex) { deployInfo.Add("no password"); deployText += "User password not deployed because a erro on decrypt password: "******"Deploy", UserLogLevel.Warning, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password not deployed because a erro on decrypt password: "******"no password"); deployText += "User password not deployed because the user is not logged in yet" + Environment.NewLine; //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Debug, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password not deployed because the user is not logged in yet"); } } else { deployInfo.Add("no password"); deployText += "User password is empty and not deployed" + Environment.NewLine; //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Debug, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password is empty and not deployed"); } //Busca todas as propriedades com o mapping deste plugin, porém com dados vindos exclusivos da entidade DataTable dtEntField = db.Select("select pf.data_name, efe.value, pf.data_type from entity_field efe inner join entity e on efe.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = efe.field_id where e.id = " + pkg.entityId + " group by pf.data_name, efe.value, pf.data_type"); if ((dtEntField != null) && (dtEntField.Rows.Count > 0)) { foreach (DataRow drEf in dtEntField.Rows) { if (!pkg.entiyData.Exists(d => (d.dataName == drEf["data_name"].ToString()))) { pkg.entiyData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString())); } } } //Busca todas as propriedades com o mapping deste plugin, porém com dados vindos dos plugins de entrada //Exclui os itens de nome e senha por ja terem sido colocados acima dtEntField = db.Select("select pf.data_name, ife.value, pf.data_type, rp.priority from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on i.resource_plugin_id = rp.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = ife.field_id where rp.enable_import = 1 and i.entity_id = " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by pf.data_name, ife.value, pf.data_type, rp.priority order by rp.priority desc, pf.data_name"); if ((dtEntField != null) && (dtEntField.Rows.Count > 0)) { foreach (DataRow drEf in dtEntField.Rows) { if (!pkg.importsPluginData.Exists(d => (d.dataName == drEf["data_name"].ToString()))) { pkg.importsPluginData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString())); } } } //Busca todas as propriedades vinculadas a este identity //Exclui os itens de nome e senha por ja terem sido colocados acima dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 inner join field f on ife.field_id = f.id where i.entity_id = " + pkg.entityId + " and i.id = " + identityId + " group by m.data_name, ife.value, f.data_type"); if ((dtEntField != null) && (dtEntField.Rows.Count > 0)) { foreach (DataRow drEf in dtEntField.Rows) { pkg.pluginData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString())); } } //Busca todas as propriedades vinculadas aos outras identity //Exclui os itens de nome e senha por ja terem sido colocados acima dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 inner join field f on ife.field_id = f.id where i.entity_id = " + pkg.entityId + " and i.id <> " + identityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by m.data_name, ife.value, f.data_type"); if ((dtEntField != null) && (dtEntField.Rows.Count > 0)) { foreach (DataRow drEf in dtEntField.Rows) { pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString())); } } //Busca todas as propriedades (independente do identity) usando o mapping deste plugin //Exclui o senha por ja tere sido colocado acima dtEntField = db.Select("select pf.data_name, ife.value, pf.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = ife.field_id where i.entity_id = " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by pf.data_name, ife.value, pf.data_type"); if ((dtEntField != null) && (dtEntField.Rows.Count > 0)) { foreach (DataRow drEf in dtEntField.Rows) { pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString())); } } //Busca todas as propriedades da tabela entity_field (exclusiva para dados manuais) usando o mapping deste plugin //Exclui o senha por ja tere sido colocado acima dtEntField = db.Select("select pf.data_name, efe.value, pf.data_type from entity_field efe inner join entity e on efe.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = efe.field_id where efe.entity_id = " + pkg.entityId + " group by pf.data_name, efe.value, pf.data_type"); if ((dtEntField != null) && (dtEntField.Rows.Count > 0)) { foreach (DataRow drEf in dtEntField.Rows) { pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString())); } } //Busca somente as propriedades marcadas como ID ou Unique property //Exclui os itens de nome e senha por ja terem sido colocados acima dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 and (m.is_unique_property = 1 or m.is_unique_property = 1) inner join field f on ife.field_id = f.id where i.entity_id = " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by m.data_name, ife.value, f.data_type"); if ((dtEntField != null) && (dtEntField.Rows.Count > 0)) { foreach (DataRow drEf in dtEntField.Rows) { pkg.ids.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString())); } } //RBAC //Ações das roles desta identity para este resource x plugin DataTable dtRoleAction = db.Select("select i.id identity_id, r.* from [identity] i inner join [entity] e on e.id = i.entity_id inner join identity_role ir on ir.identity_id = i.id inner join (select rp.id resource_plugin_id, rp.plugin_id, rp.resource_id, r.name role_name, rpa.id action_id, rpa.role_id, rpa.action_key, rpa.action_add_value, rpa.action_del_value, rpa.additional_data from resource_plugin rp inner join resource_plugin_role rpr on rpr.resource_plugin_id = rp.id inner join resource_plugin_role_action rpa on rpa.resource_plugin_id = rp.id inner join [role] r on r.id = rpa.role_id and r.id = rpr.role_id) r on r.role_id = ir.role_id where r.resource_plugin_id = " + resourcePluginId + " AND e.id = " + entityId); if ((dtRoleAction != null) && (dtRoleAction.Rows.Count > 0)) { foreach (DataRow drR in dtRoleAction.Rows) { pkg.pluginAction.Add(new PluginConnectorBaseDeployPackageAction(PluginActionType.Add, drR["role_name"].ToString(), drR["action_key"].ToString(), drR["action_add_value"].ToString(), (drR["additional_data"] != DBNull.Value ? drR["additional_data"].ToString() : null))); //db.AddUserLog(LogKey.Role_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Role: " + drR["role_name"].ToString()); deployInfo.Add("role " + drR["role_name"].ToString()); deployText += "role " + drR["role_name"].ToString() + Environment.NewLine; } } db.AddUserLog(LogKey.Role_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Identity addedd in deploy package with: " + String.Join(", ", deployInfo), deployText); } finally { if (deployInfo != null) { deployInfo.Clear(); } deployInfo = null; deployText = ""; } return(pkg); }
private void ProcQueue(FileInfo f, Object oStarter) { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 900; Boolean rebuildIndex = false; String type = ""; type = ""; JSONRequest req = null; try { using (FileStream fs = f.OpenRead()) req = JSON.GetRequest(fs); if ((req.host == null) || (req.host == "")) { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'host' is empty on " + f.Name); return; } if ((req.enterpriseid == null) || (req.enterpriseid == "")) { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is empty on " + f.Name); return; } try { Int64 tst = Int64.Parse(req.enterpriseid); } catch { if ((req.enterpriseid == null) || (req.enterpriseid == "")) { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is not Int64 " + f.Name); return; } } ProxyConfig config = new ProxyConfig(true); config.GetDBCertConfig(db.Connection, Int64.Parse(req.enterpriseid), req.host); if (config.fqdn != null) //Encontrou o proxy { JsonGeneric jData = new JsonGeneric(); try { String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), Convert.FromBase64String(req.data))) jData.FromJsonBytes(cApi.clearData); } catch (Exception ex) { jData = null; db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Error on decrypt package data " + f.Name + " for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message); } if (jData == null) { return; } type = jData.function.ToLower(); switch (type) { case "processimport-disabled": rebuildIndex = true; //ImportRegisters(config, jData, f, req, db); f.Delete(); break; case "processimportv2": rebuildIndex = true; last_status = "Executando importação de registros"; ImportRegistersV2(config, jData, f, req, db); f.Delete(); break; case "processstructimport": last_status = "Executando importação de registros de estrutura"; ImportRegistersStruct(config, jData, f, req, db); f.Delete(); break; case "notify": last_status = "Executando importação de notificações"; ImportNotify(config, jData, f, req, db); f.Delete(); break; case "deleted": last_status = "Executando importação de exclusões"; ImportDelete(config, jData, f, req, db); f.Delete(); break; case "logrecords": last_status = "Executando importação de logs"; ImportLogs(config, jData, f, req, db); f.Delete(); //f.MoveTo(f.FullName + ".imported"); break; case "packagetrack": last_status = "Executando importação de track dos pacotes"; ImportPackageTrack(config, jData, f, req, db); f.Delete(); //f.MoveTo(f.FullName + ".imported"); break; default: db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Invalid jData function '" + jData.function + "'"); break; } } else { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Proxy config not found for enterprise " + req.enterpriseid + " and proxy " + req.host); } config = null; } catch (Exception ex) { TextLog.Log("Inbound", "Erro on process file '" + f.Name + "' (" + type + "): " + ex.Message); db.AddUserLog(LogKey.Import, null, "Inbound", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Erro processing file '" + f.Name + "' (" + type + "): " + ex.Message); } finally { last_status = ""; req = null; filesProcessed++; } /* * if (rebuildIndex) * { * db.Timeout = 900; * last_status = "Reindexando registros"; * db.ExecuteNonQuery("sp_reindex_imports", CommandType.StoredProcedure, null); * }*/ } catch (Exception ex) { TextLog.Log("Inbound", "Error importing file (" + f.Name + ")" + ex.Message); } finally { if (db != null) { db.closeDB(); } } }
public NoxBinaryReader(Stream stream, CryptApi.NoxCryptFormat format) : base(CryptApi.DecryptStream(stream, format)) { }
protected void Page_Load(object sender, EventArgs e) { Request.InputStream.Position = 0; try { JSONRequest req = JSON.GetRequest(Request.InputStream); 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) //Encontrou o proxy { try { Byte[] bData = Convert.FromBase64String(req.data); List <Dictionary <String, Object> > proccessData = new List <Dictionary <string, object> >(); String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), bData)) proccessData = SafeTrend.Json.JSON.Deserialize <List <Dictionary <String, Object> > >(Encoding.UTF8.GetString(cApi.clearData)); foreach (Dictionary <String, Object> p in proccessData) { if (p.ContainsKey("fetch_id")) { String jData = SafeTrend.Json.JSON.Serialize2(p); Int64 fetch_id = 0; try { fetch_id = Int64.Parse(p["fetch_id"].ToString()); } catch { } if (fetch_id > 0) { DbParameterCollection par = new DbParameterCollection(); par.Add("@fetch_id", typeof(Int64)).Value = fetch_id; par.Add("@json_data", typeof(String)).Value = jData; par.Add("@success", typeof(Boolean)).Value = (p.ContainsKey("result") && (p["result"] is Boolean) && (Boolean)p["result"]); db.ExecuteNonQuery("update resource_plugin_fetch set response_date = getdate(), [success] = @success, json_data = @json_data WHERE id = @fetch_id", System.Data.CommandType.Text, par); } } } ReturnHolder.Controls.Add(new LiteralControl("{ \"response\":\"success\" }")); } catch { ReturnHolder.Controls.Add(new LiteralControl("{ \"response\":\"error\" }")); } } } } catch (Exception ex) { Tools.Tool.notifyException(ex, this); throw ex; } }
private void ExecuteConnector(Boolean deployOnly) { List <Int64> resource_plugin = new List <Int64>(); //Separa os contextos String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); OpenSSL.X509.X509Certificate cert = CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass); try { foreach (PluginConfig p in config.plugins) { if (p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower()) { JsonGeneric pgConf = new JsonGeneric(); try { using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters))) pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData)); } catch (Exception ex) { throw new Exception("Decrypt error1 " + ex.Message); } finally { pgConf = null; } if (!resource_plugin.Contains(p.resource_plugin)) { resource_plugin.Add(p.resource_plugin); } } } foreach (Int64 rp in resource_plugin) { DebugLog("{" + plugin.GetPluginId().AbsoluteUri + "} Resource plugin " + rp); Dictionary <String, Object> connectorConf = new Dictionary <String, Object>(); List <PluginConnectorBaseDeployPackageMapping> mapping = new List <PluginConnectorBaseDeployPackageMapping>(); Boolean enableDeploy = false; Int64 r = 0; try { foreach (PluginConfig p in config.plugins) { if ((p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower()) && (p.resource_plugin == rp)) { r = p.resource; Dictionary <String, String> tmp = new Dictionary <string, string>(); foreach (PluginConfigMapping m in p.mapping) { mapping.Add(new PluginConnectorBaseDeployPackageMapping(m.data_name, m.data_type, m.is_id, m.is_unique_property, m.is_password, m.is_login, m.is_name)); } enableDeploy = p.enable_deploy; JsonGeneric pgConf = new JsonGeneric(); try { if (cert == null) { throw new Exception("Certificate is null"); } using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters))) pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData)); } catch (Exception ex) { throw new Exception("Decrypt error: " + ex.Message); } if ((pgConf.data == null) || (pgConf.data.Count == 0)) { continue; } Int32 kCol = pgConf.GetKeyIndex("key"); Int32 vCol = pgConf.GetKeyIndex("value"); if (!String.IsNullOrWhiteSpace(p.mail_domain)) { PluginBase.FillConfig(plugin, ref connectorConf, "iam_mail_domain", p.mail_domain); } //connectorConf.Add("iam_mail_domain", p.mail_domain); foreach (String[] d1 in pgConf.data) { PluginBase.FillConfig(plugin, ref connectorConf, d1[kCol], d1[vCol].ToString()); } /* * if (!connectorConf.ContainsKey(d1[kCol])) * connectorConf.Add(d1[kCol], d1[vCol].ToString());*/ } } //Deploy ocorre antes da importação //Para que na importação ja apareça os registros que foram publicados pelo deploy try { System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(plugin.GetType()); DirectoryInfo dirFrom = new DirectoryInfo(Path.Combine(basePath, "In\\" + Path.GetFileNameWithoutExtension(asm.Location) + "\\rp" + rp)); DebugLog("{" + plugin.GetPluginId().AbsoluteUri + "} RP =" + rp + ", r = " + r + " => path " + dirFrom.FullName + ", exists? " + dirFrom.Exists); if (enableDeploy) { //Verifica se há algo para processar if (dirFrom.Exists) { ProcessDeploy(r, rp, connectorConf, mapping); } } else { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Deploy disabled"); //Exclui os arquivos if (dirFrom.Exists) { foreach (FileInfo f in dirFrom.GetFiles("*.iamdat")) { f.Delete(); } } } } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on deploy: " + ex.Message); } if (!deployOnly) { try { //O import não é desabilitado, pois ele é necessário para relatório de consistência //o Engine não utilizará ele para adicionar novas entidades ProcessImport(r, rp, connectorConf, mapping); } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on import: " + ex.Message); } } executionCount++; if (executionCount > 50) { executionCount = 0; TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Cleaning up proccess"); System.Diagnostics.Process.GetCurrentProcess().Kill(); } } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on parse config: " + ex.Message); } finally { connectorConf.Clear(); connectorConf = null; mapping.Clear(); mapping = null; } } } finally { cert = null; certPass = null; } }
private static void ParseMonsterBin() { using (StreamReader rdr = new StreamReader(CryptApi.DecryptStream(GetStream(), CryptApi.NoxCryptFormat.MONSTER))) { string line; MonsterInfo minfo = new MonsterInfo(); bool monsterBlock = false; while (!rdr.EndOfStream) { line = rdr.ReadLine(); if (!monsterBlock && line.Length > 1) { minfo = new MonsterInfo(); minfo.Name = line; monsterBlock = true; continue; } if (line == "END") { monsterBlock = false; MonsterDict.Add(minfo.Name, minfo); continue; } string[] split = line.Split(' '); string type = "", val = ""; foreach (string s in split) { if (s.Length > 0) { if (s == "ARENA") { break; // ignore arena entries } if (s == "SOLO") { continue; } if (type.Length == 0) { type = s; } else { val = s; } } } switch (type) { case "HEALTH": minfo.Health = int.Parse(val); break; case "RETREAT_RATIO": minfo.RetreatRatio = float.Parse(val, NumberFormatInfo.InvariantInfo); break; case "RESUME_RATIO": minfo.ResumeRatio = float.Parse(val, NumberFormatInfo.InvariantInfo); break; case "STATUS": minfo.Status = val; break; } } } }
static void Main(string[] args) { ServerLocalConfig localConfig = new ServerLocalConfig(); localConfig.LoadConfig(); if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == "")) { StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == "")) { StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == "")) { StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == "")) { StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null); } /************* * Gera os certificados do servidor */ MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 300; Int64 entityId = 0; if (args.Length > 0) { Int64.TryParse(args[0], out entityId); } DataTable tmp = db.Select(String.Format("select e.*, e1.id enterprise_id from entity e inner join context c on c.id = e.context_id inner join enterprise e1 on e1.id = c.enterprise_id where e.id = {0}", entityId)); if (tmp == null) { StopOnError("Select is null", null); } if (tmp.Rows.Count == 0) { StopOnError("Select is empty", null); } EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.conn, (Int64)tmp.Rows[0]["entity_id"]); Int64 context = (Int64)tmp.Rows[0]["context_id"]; Int64 enterpriseId = (Int64)tmp.Rows[0]["enterprise_id"]; Console.WriteLine("##############################"); Console.WriteLine("C Pwd: " + tmp.Rows[0]["password"].ToString()); Console.WriteLine(""); Console.WriteLine("##############################"); using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(tmp.Rows[0]["password"].ToString()))) Console.WriteLine("Pwd: " + Encoding.UTF8.GetString(cApi.clearData)); String text = ""; do { //Console.Clear(); Console.Write("Deseja redefinir a senha do usuário? (Y/N): "); text = Console.ReadLine().Trim(); if (text.ToLower() == "y") { break; } else if (text.ToLower() == "n") { text = ""; break; } else { text = ""; } } while (text == ""); if (text.ToLower() == "y") { BuildPassword(db, null, context, entityId, enterpriseId); } db.closeDB(); StopOnError("", null); }
private void StartAgents() { List <Int64> resource = new List <Int64>(); //Separa os contextos String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); OpenSSL.X509.X509Certificate cert = CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass); try { foreach (PluginConfig p in config.plugins) { if (p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower()) { Dictionary <String, Object> connectorConf = new Dictionary <String, Object>(); JsonGeneric pgConf = new JsonGeneric(); try { if (cert == null) { throw new Exception("Certificate is null"); } using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters))) pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData)); } catch (Exception ex) { throw new Exception("Decrypt error: " + ex.Message); } if ((pgConf.data == null) || (pgConf.data.Count == 0)) { continue; } Int32 kCol = pgConf.GetKeyIndex("key"); Int32 vCol = pgConf.GetKeyIndex("value"); foreach (String[] d1 in pgConf.data) { PluginBase.FillConfig(plugin, ref connectorConf, d1[kCol], d1[vCol].ToString()); } /*if (!connectorConf.ContainsKey(d1[kCol])) * connectorConf.Add(d1[kCol], d1[vCol].ToString());*/ try { StartAgents(connectorConf); } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on start agent: " + ex.Message); } finally { connectorConf.Clear(); connectorConf = null; } } } } catch (Exception ex) { TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on parse config: " + ex.Message); } cert = null; certPass = null; }
public void Commit() { //Grava as informações no banco de dados SqlTransaction trans = db.Connection.BeginTransaction(); try { //Cria a empresa DbParameterCollection par = new DbParameterCollection(); par.Add("@name", typeof(String), this.name.Length).Value = this.name; par.Add("@fqdn", typeof(String), this.fqdn.Length).Value = this.fqdn; par.Add("@server_pkcs12_cert", typeof(String), this.ServerPKCS12Cert.Length).Value = this.ServerPKCS12Cert; par.Add("@server_cert", typeof(String), this.ServerCert.Length).Value = this.ServerCert; par.Add("@client_pkcs12_cert", typeof(String), this.ClientPKCS12Cert.Length).Value = this.ClientPKCS12Cert; par.Add("@language", typeof(String), this.language.Length).Value = this.language; par.Add("@auth_plugin", typeof(String)).Value = "auth://iam/plugins/internal"; Int64 enterpriseId = db.ExecuteScalar <Int64>("sp_new_enterprise", CommandType.StoredProcedure, par, trans); //Insere os campos padrões da empresa par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@field_name", typeof(String)).Value = "Nome"; par.Add("@data_type", typeof(String)).Value = "String"; par.Add("@public", typeof(Boolean)).Value = false; par.Add("@user", typeof(Boolean)).Value = false; DataTable dtField = db.ExecuteDataTable("[sp_new_field]", CommandType.StoredProcedure, par, trans); Int64 nameFieldId = (Int64)dtField.Rows[0]["id"]; par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@field_name", typeof(String)).Value = "Login"; par.Add("@data_type", typeof(String)).Value = "String"; par.Add("@public", typeof(Boolean)).Value = false; par.Add("@user", typeof(Boolean)).Value = false; dtField = db.ExecuteDataTable("[sp_new_field]", CommandType.StoredProcedure, par, trans); Int64 loginFieldId = (Int64)dtField.Rows[0]["id"]; par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@field_name", typeof(String)).Value = "E-mail"; par.Add("@data_type", typeof(String)).Value = "String"; par.Add("@public", typeof(Boolean)).Value = false; par.Add("@user", typeof(Boolean)).Value = false; db.ExecuteNonQuery("[sp_new_field]", CommandType.StoredProcedure, par, trans); par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@field_name", typeof(String)).Value = "Senha"; par.Add("@data_type", typeof(String)).Value = "String"; par.Add("@public", typeof(Boolean)).Value = false; par.Add("@user", typeof(Boolean)).Value = false; db.ExecuteNonQuery("[sp_new_field]", CommandType.StoredProcedure, par, trans); //Cria o contexto par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@name", typeof(String), 7).Value = "Default"; par.Add("@password_rule", typeof(String), 15).Value = "default[123456]"; par.Add("@pwd_length", typeof(Int32)).Value = 8; par.Add("@pwd_upper_case", typeof(Boolean)).Value = true; par.Add("@pwd_lower_case", typeof(Boolean)).Value = true; par.Add("@pwd_digit", typeof(Boolean)).Value = true; par.Add("@pwd_symbol", typeof(Boolean)).Value = true; par.Add("@pwd_no_name", typeof(Boolean)).Value = true; Int64 contextId = db.ExecuteScalar <Int64>("sp_new_context", CommandType.StoredProcedure, par, trans); //Cria a role de sistema de administrador desta empresa par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@name", typeof(String)).Value = "Enterprise Admin"; par.Add("@system_admin", typeof(Boolean)).Value = false; par.Add("@enterprise_admin", typeof(Boolean)).Value = true; Int64 sysRoleId = db.ExecuteScalar <Int64>("sp_new_sys_role", CommandType.StoredProcedure, par, trans); //Cria o usuário administrador par = new DbParameterCollection(); par.Add("@context_id", typeof(Int64)).Value = contextId; par.Add("@alias", typeof(String)).Value = "Admin"; par.Add("@login", typeof(String)).Value = "admin"; par.Add("@full_name", typeof(String)).Value = "Admin"; using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId, trans)) using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes("123456"))) par.Add("@password", typeof(String)).Value = Convert.ToBase64String(cApi.ToBytes()); Int64 entityId = db.ExecuteScalar <Int64>("sp_new_entity", CommandType.StoredProcedure, par, trans); //Vincula o usuário na role de sistema como enterprise admin db.ExecuteNonQuery("insert into sys_entity_role (entity_id, role_id) values(" + entityId + "," + sysRoleId + ")", CommandType.Text, null, trans); //Cria informação na tabela entity_field para o usuário poder aparecer nas consultas db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + entityId + "," + nameFieldId + ",'Admin')", CommandType.Text, null, trans); db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + entityId + "," + loginFieldId + ",'admin')", CommandType.Text, null, trans); //Cria o usuário de integração do CAS par = new DbParameterCollection(); par.Add("@context_id", typeof(Int64)).Value = contextId; par.Add("@alias", typeof(String)).Value = "Integração CAS"; par.Add("@login", typeof(String)).Value = "integracao.cas"; par.Add("@full_name", typeof(String)).Value = "Integração CAS"; using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId, trans)) using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes("123456"))) par.Add("@password", typeof(String)).Value = Convert.ToBase64String(cApi.ToBytes()); Int64 casEntityId = db.ExecuteScalar <Int64>("sp_new_entity", CommandType.StoredProcedure, par, trans); //Vincula o usuário na role de sistema como enterprise admin db.ExecuteNonQuery("insert into sys_entity_role (entity_id, role_id) values(" + casEntityId + "," + sysRoleId + ")", CommandType.Text, null, trans); //Cria informação na tabela entity_field para o usuário poder aparecer nas consultas db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + casEntityId + "," + nameFieldId + ",'Admin')", CommandType.Text, null, trans); db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + casEntityId + "," + loginFieldId + ",'admin')", CommandType.Text, null, trans); //Cria as regras padrões de criação de login db.ExecuteNonQuery("INSERT INTO [login_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, lastname','first_name,dot,last_name',1)", CommandType.Text, null, trans); db.ExecuteNonQuery("INSERT INTO [login_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'Fistname, second name','first_name,dot,second_name',2)", CommandType.Text, null, trans); db.ExecuteNonQuery("INSERT INTO [login_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, last name, index','first_name,dot,last_name,index',3)", CommandType.Text, null, trans); //Cria as regras padrões de criação de e-mail db.ExecuteNonQuery("INSERT INTO [st_mail_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, lastname','first_name,dot,last_name',1)", CommandType.Text, null, trans); db.ExecuteNonQuery("INSERT INTO [st_mail_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'Fistname, second name','first_name,dot,second_name',2)", CommandType.Text, null, trans); db.ExecuteNonQuery("INSERT INTO [st_mail_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, last name, index','first_name,dot,last_name,index',3)", CommandType.Text, null, trans); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw ex; } }
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())); } }
public void RenewCert(SqlConnection conn, SqlTransaction transaction) { SqlTransaction trans = transaction; base.Connection = conn; if (trans == null) { trans = conn.BeginTransaction(); } DataTable dt = ExecuteDataTable("select fqdn, server_cert, server_pkcs12_cert, client_pkcs12_cert from enterprise with(nolock) where id = " + this.enterpriseId, trans); if ((dt == null) || (dt.Rows.Count == 0)) //Não encontrou a empresa { throw new Exception("Enterprise '" + enterpriseId + "' not found"); } System.Security.Cryptography.SHA1Managed sha = new System.Security.Cryptography.SHA1Managed(); Byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(dt.Rows[0]["fqdn"].ToString())); String key = BitConverter.ToString(hash).Replace("-", ""); //Resgata o certificado do banco X509Certificate atualServerPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(dt.Rows[0]["server_pkcs12_cert"].ToString()), key); X509Certificate atualClientPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(dt.Rows[0]["client_pkcs12_cert"].ToString()), key); //Se tudo OK, inicia o processo try { //Cria o novo certificado, e a chave se não existir ainda this.BuildCert(conn, trans); //Exclui o certificado atual do banco //ExecuteSQL(conn, "delete from server_cert", null, CommandType.Text, trans); //Salva o novo certificado DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this.enterpriseId; par.Add("@server_cert", typeof(String)).Value = this.ServerCertString; par.Add("@server_pkcs12_cert", typeof(String)).Value = this.ServerPKCS12String; par.Add("@client_pkcs12_cert", typeof(String)).Value = this.ClientPKCS12String; ExecuteNonQuery("update enterprise set server_cert = @server_cert, server_pkcs12_cert = @server_pkcs12_cert, client_pkcs12_cert = @client_pkcs12_cert where id = @enterprise_id", CommandType.Text, par, trans); //Criptografa a senha de todas as entidades DataTable dtEnt = ExecuteDataTable("select e.id, e.login, e.password from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id inner join enterprise e1 with(nolock) on e1.id = c.enterprise_id where e1.id = " + this.enterpriseId, trans); if (dtEnt == null) { throw new Exception("Erro on SQL"); } foreach (DataRow dr in dtEnt.Rows) { Console.Write("[EK] Entity " + dr["id"] + ": "); try { using (CryptApi decryptApi = CryptApi.ParsePackage(atualServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString()))) using (CryptApi ecryptApi = new CryptApi(this.ServerCert, decryptApi.clearData)) { DbParameterCollection pPar = new DbParameterCollection(); String b64 = Convert.ToBase64String(ecryptApi.ToBytes()); pPar.Add("@password", typeof(String), b64.Length).Value = b64; Exception ex1 = null; for (Int32 count = 1; count <= 3; count++) { try { ExecuteNonQuery("update entity set password = @password where id = " + dr["id"], CommandType.Text, pPar, trans); ex1 = null; break; } catch (Exception ex) { ex1 = ex; if (ex.Message.ToLower().IndexOf("timeout") != -1) { System.Threading.Thread.Sleep(1000 * count); } } } if (ex1 != null) { throw ex1; } Log(this.enterpriseId.ToString(), dr["id"].ToString(), dr["login"].ToString(), Encoding.UTF8.GetString(decryptApi.clearData)); Console.WriteLine("OK"); } } catch (Exception ex) { Console.WriteLine("Err"); throw ex; } } try { System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(ServerKey2)); FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "eCerts\\" + dt.Rows[0]["fqdn"].ToString() + ".cer")); if (certFile.Exists) { certFile.Delete(); } if (!certFile.Directory.Exists) { certFile.Directory.Create(); } File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(this.ServerCertString)); } catch { } //Se tudo estiver OK, realiza o commit dos dados Console.WriteLine("Commit"); if (transaction == null) { trans.Commit(); } } catch (Exception ex) { Console.WriteLine("Rollback"); if (transaction == null) { trans.Rollback(); } throw ex; } }
private void BuildBackup() { StringBuilder bkpLog = new StringBuilder(); IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); bkpLog.AppendLine("Listando tabelas da base de dados..."); DataTable dtS = db.Select("select TABLE_NAME from information_schema.tables where TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME"); if ((dtS == null) || (dtS.Rows.Count == 0)) { bkpLog.AppendLine("Listagem de tabelas vazia ou nula"); throw new Exception("Table list is null or empty"); } bkpLog.AppendLine(dtS.Rows.Count + " tabelas"); FileInfo bkpFile = new FileInfo(Path.Combine(Path.Combine(basePath, "Backup"), "bkp-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ".iambkp")); if (!bkpFile.Directory.Exists) { bkpFile.Directory.Create(); } bkpLog.AppendLine("Criando arquivo de backup: " + bkpFile.FullName); using (SqliteBase exportDB = new SqliteBase(bkpFile)) { foreach (DataRow drSrc in dtS.Rows) { String tableName = drSrc["TABLE_NAME"].ToString(); bkpLog.AppendLine("Exportando tabela: " + tableName); Console.WriteLine(tableName); DataTable dtSchema = db.GetSchema(tableName); StringBuilder createCmd = new StringBuilder(); createCmd.AppendLine("DROP TABLE IF EXISTS [" + tableName.ToLower() + "];"); /* * CREATE TABLE [Events] ( * id INTEGER PRIMARY KEY AUTOINCREMENT, * test_id TEXT NOT NULL, * date datetime not null DEFAULT (datetime('now','localtime')), * event_text TEXT NULL * );*/ List <String> columns = new List <string>(); bkpLog.AppendLine("Criando estrutura da tabela"); try { foreach (DataColumn dc in dtSchema.Columns) { if (dc.DataType.Equals(typeof(Int32)) || dc.DataType.Equals(typeof(Int64))) { columns.Add("[" + dc.ColumnName + "] INTEGER NULL"); } else if (dc.DataType.Equals(typeof(DateTime))) { columns.Add("[" + dc.ColumnName + "] datetime NULL"); } else { columns.Add("[" + dc.ColumnName + "] TEXT NULL"); } } } catch (Exception ex) { bkpLog.AppendLine("Erro ao listar as colunas da tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro ao listar as colunas da tabela '" + tableName + "': " + ex.Message); throw ex; } try { createCmd.AppendLine("CREATE TABLE [" + tableName.ToLower() + "] ("); createCmd.AppendLine(String.Join(", " + Environment.NewLine, columns)); createCmd.AppendLine(");"); exportDB.ExecuteNonQuery(createCmd.ToString()); } catch (Exception ex) { bkpLog.AppendLine("Erro ao criando tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro ao criando tabela '" + tableName + "': " + ex.Message); throw ex; } //Copiando dados das tabelas try { bkpLog.AppendLine("Copiando dados"); if (tableName.ToLower() == "logs") { DataTable dtSrcData = db.ExecuteDataTable("select l.* from [logs] l with(nolock) inner join [entity_timeline] et with(nolock) on et.log_id = l.id"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } else if (tableName.ToLower() == "entity") { DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } else { DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } } catch (Exception ex) { bkpLog.AppendLine("Erro copiando dados da tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro copiando dados da tabela '" + tableName + "': " + ex.Message); //throw ex; } } //No final de todo o processo atualiza as senhas como cleartext try { bkpLog.AppendLine("Atualizando as senhas das entidades"); DataTable dtEnt = db.ExecuteDataTable("select id from [enterprise] with(nolock)"); foreach (DataRow drEnt in dtEnt.Rows) { using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)drEnt["id"])) { DataTable dtSrcData = db.ExecuteDataTable("select e.id, e.password, c.enterprise_id from [entity] e with(nolock) inner join [context] c with(nolock) on e.context_id = c.id where c.enterprise_id = " + drEnt["id"]); //Atualiza senha em clear text de cada usu[ario foreach (DataRow drUser in dtSrcData.Rows) { try { using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(drUser["password"].ToString()))) { exportDB.ExecuteNonQuery("update entity set password = '******' where id = " + drUser["id"]); } } catch (Exception ex) { bkpLog.AppendLine("Erro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message); TextLog.Log("Backup", "\tErro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message); //throw ex; } } } } } catch (Exception ex) { bkpLog.AppendLine("Erro atualizando as senhas para cleartext: " + ex.Message); TextLog.Log("Backup", "\tErro atualizando as senhas para cleartext: " + ex.Message); //throw ex; } } db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Backup realizado com sucesso", bkpLog.ToString()); } catch (Exception ex) { TextLog.Log("Backup", "\tError building backup: " + ex.Message); bkpLog.AppendLine("Error building backup: " + ex.Message); try { db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Backup finalizado com erro", bkpLog.ToString()); } catch { } } finally { if (bkpLog != null) { bkpLog = null; } if (db != null) { db.Dispose(); } } }
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; } }
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)); } }
public LoginResult LocalAuth(IAMDatabase database, System.Web.UI.Page page, String username, String password, Boolean byPassPasswordCheck) { 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; } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@login", typeof(String), username.Length).Value = username; DataTable tmp = null; tmp = database.ExecuteDataTable("select distinct id, alias, full_name, login, enterprise_id, password, must_change_password from vw_entity_logins with(nolock) where deleted = 0 and enterprise_id = @enterprise_id and locked = 0 and (login = @login or value = @login)", CommandType.Text, par); if ((tmp != null) && (tmp.Rows.Count > 0)) { foreach (DataRow dr in tmp.Rows) { using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(database.Connection, enterpriseId)) using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString()))) if (byPassPasswordCheck || Encoding.UTF8.GetString(cApi.clearData) == password) { Random rnd = new Random(); 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.SecurityToken = (Byte)rnd.Next(1, 255); SetLoginSession(page, l); database.ExecuteNonQuery("update entity set last_login = getdate() where id = " + l.Id, CommandType.Text, null); database.AddUserLog(LogKey.User_Logged, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, l.Id, 0, MessageResource.GetMessage("user_logged") + " " + GetIPAddress(page), "{ \"ipaddr\":\"" + GetIPAddress(page) + "\"} "); return(new LoginResult(true, "User OK", (Boolean)tmp.Rows[0]["must_change_password"])); break; } else { database.AddUserLog(LogKey.User_WrongPassword, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, (Int64)tmp.Rows[0]["id"], 0, MessageResource.GetMessage("user_wrong_password") + " " + GetIPAddress(page), "{ \"ipaddr\":\"" + GetIPAddress(page) + "\"} "); } } return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"))); } else { database.AddUserLog(LogKey.User_WrongUserAndPassword, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, MessageResource.GetMessage("user_wrong_password") + " " + GetIPAddress(page), "{ \"username\":\"" + username.Replace("'", "").Replace("\"", "") + "\", \"ipaddr\":\"" + GetIPAddress(page) + "\"} "); return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"))); } } catch (Exception ex) { //Tools.Tool.notifyException(ex, page); return(new LoginResult(false, "Internal error", ex.Message)); } finally { } }