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 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(); } } }
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); }
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 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; } }
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 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; } }
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 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; } }
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); }
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; } }