public static void CreatePassKey(string passKey) { try { RegistryKey software = Registry.LocalMachine.OpenSubKey("Software", true); if (software == null) { Console.WriteLine("Could not access registry, please run this program 'As Administrator'"); return; } RegistryKey symplus = software.OpenSubKey("Symplus", true); if (symplus == null) { symplus = software.CreateSubKey("Symplus"); symplus = software.OpenSubKey("Symplus", true); } RegistryKey version = symplus.OpenSubKey("Verion", true); if (version == null) { version = symplus.CreateSubKey("Version"); //version = symplus.OpenSubKey("Verion", true); } version.SetValue("Key", passKey); } catch (System.Security.SecurityException ex) { RbacException.Raise("There was an error occurred, may be because RBAC is running first time on this computer, try executing RBAC with administratitve rights!"); } }
/// <summary> /// This instance is allowed to call only from test bed - todo security /// </summary> /// <param name="userName">The logged in user name</param> /// <param name="rbacName">The overridden rbac name, empty will use user's default</param> /// <param name="roleName">The overriden role name, empty will use user's default</param> public Rbac(string userName, string rbacName, string roleName) { //no cache will be implemented DataManager.Manager manager = new DataManager.Manager(false); RbacUser user = new RbacUser(userName); if (!string.IsNullOrEmpty(roleName)) { user.Role = new RbacRole(roleName); //override role } if (user.Role == null) { RbacException.Raise(string.Format("The role '{0}' is not found!", roleName), RbacExceptionCategories.Repository); } Rbac dbRbac = null; if (!string.IsNullOrEmpty(rbacName)) { dbRbac = manager.GetRbac(rbacName); //override rbac } else { dbRbac = manager.GetRbac(user.Role.RbacId); } if (dbRbac == null) { RbacException.Raise(string.Format("The rbac '{0}' was not defined yet!", rbacName), RbacExceptionCategories.Repository); } dbRbac.User = user; Assign(dbRbac); }
public void ApplyPermissionUpdate() { var tables = Columns.GroupBy(c => c.Table.Name).Select(grp => grp.ToList()).ToList(); foreach (var allColumnnsInATable in tables) { if (allColumnnsInATable.Count > 0) { RbacTable rbacTable = TablesReferred.Find(allColumnnsInATable[0].Table.Name); if (rbacTable == null) { throw new Exception("Could not find table name in referred tables!"); } if (rbacTable.AllowedOperations.HasFlag(RbacDBOperations.Update)) { foreach (RbacSelectColumn column in allColumnnsInATable) { RbacColumn rbacColumn = rbacTable.FindColumn(column.Name); if (!rbacColumn.AllowedOperations.HasFlag(RbacDBOperations.Update)) { RbacException.Raise(string.Format("User '{0}' has permission to update table '{1}', however has no permission to update column '{2}'!", Context.User.UserName, rbacTable.Name, rbacColumn.Name), RbacExceptionCategories.Parser); } } } else { RbacException.Raise(string.Format("User '{0}' does not have permission to update table '{1}'!", Context.User.UserName, rbacTable.Name), RbacExceptionCategories.Parser); } } } IsPermissionApplied = true; }
private void ParseSqlDeleteStatement(TSqlStatement sqlStatement) { if (sqlStatement.GetType() == typeof(DeleteStatement)) { DeleteStatement aDeleteStatement = (DeleteStatement)sqlStatement; #region Handle Target Table NamedTableReferenceVisitor ntVisitor = new NamedTableReferenceVisitor(Context); aDeleteStatement.DeleteSpecification.Target.Accept(ntVisitor); TablesReferred = ntVisitor.Tables; if (TablesReferred.Count == 0) { RbacException.Raise("No target table found in the delete query!"); } else if (TablesReferred.Count != 1) { RbacException.Raise("More than 1 target tables found in the delete query! Currently not supported."); } #endregion Handle Target Table //UpdateReferredTables(targetTable.Name, targetTable.Alias); } else { Errors.Add("Not a update statement!"); } }
public static void ParseReferenceTableNames(this List <RbacWhereClause> whereClauses, List <RbacJoin> joinClauses) { if (joinClauses.Count == 0) { return; } foreach (RbacWhereClause wClause in whereClauses) { var r = joinClauses.Where(jc => jc.FromTableAlias.Equals(wClause.OnTableAlias)).SingleOrDefault(); if (r != null) { wClause.OnTable = r.FromTableName; } else { r = joinClauses.Where(jc => jc.WithTableAlias.Equals(wClause.OnTableAlias)).SingleOrDefault(); if (r != null) { wClause.OnTable = r.WithTableName; } else { RbacException.Raise(string.Format("Something went wrong, the table alias '{0}' found in the where condition was not found in referred table list!", wClause.OnTableAlias)); } } } }
public bool Authenticate(string password) { IsAuthenticated = new DataManager.Manager().Authenticate(this.RbacId, password); if (!IsAuthenticated) { RbacException.Raise("Incorrect password!"); } return(IsAuthenticated); }
public static Rbac GetRbac(string rbacName) { Rbac dbRbac = new DataManager.Manager(false).GetRbac(rbacName); if (dbRbac == null) { RbacException.Raise(string.Format("Rbac '{0}' was not defined yet!", rbacName), RbacExceptionCategories.Web); } return(dbRbac); }
public RbacUser(string userName) { RbacUser user = new DataManager.Manager(false).GetUser(userName); if (user == null) { RbacException.Raise(string.Format("User not found with username as '{0}'!", userName), RbacExceptionCategories.Repository); } Assign(user); PopulateParameters(); }
public RbacRole(string roleName) { RbacRole role = new DataManager.Manager(false).GetRole(roleName); if (role == null) { RbacException.Raise(string.Format("Role '{0}' was not foundin repository!", roleName), RbacExceptionCategories.Repository); } Assign(role); ParseMetaData(); }
public void ApplyPermissionDelete() { foreach (var table in TablesReferred) { if (!table.AllowedOperations.HasFlag(RbacDBOperations.Delete)) { RbacException.Raise(string.Format("User '{0}' does not have permission to delete record from table '{1}'!", Context.User.UserName, table.Name), RbacExceptionCategories.Parser); } } IsPermissionApplied = true; }
private void RemoveColumnFromSelect(RbacSelectColumn column) { //if (column.TableColumnName == "SSN") // Debugger.Break(); SelectColumnRemover selectColumnRemover = new SelectColumnRemover(ParsedQuery, column); ParsedQuery = selectColumnRemover.Remove(); if ((IsSilent == false) && selectColumnRemover.IsZeroSelectColumn) { RbacException.Raise("The query returned 0(zero) column!"); } }
private void ParseQuery(string query) { if (string.IsNullOrEmpty(query)) { RbacException.Raise("Cannot parse an empty query!"); } OriginalQuery = query; ParsedQuery = query; if (!IsParsingSkipped) { ExecutionTime.Start(ExecutionTimeTrackers.ParseQuery); ParseQueryType(); ParseInternal(query); ExecutionTime.Stop(ExecutionTimeTrackers.ParseQuery); if (!IsParsed) { return; } if (QueryType == RbacQueryTypes.Select) { ExecutionTime.Start(ExecutionTimeTrackers.ConditionsNRelations); ApplyConditions(); ApplyConditionsRelational(); ParsedQuery = JoinClauses.ParseQuery(ParsedQuery); ExecutionTime.Stop(ExecutionTimeTrackers.ConditionsNRelations); } } else { Errors.Add("Parsing skipped!"); } ExecutionTime.Start(ExecutionTimeTrackers.ApplyPermissions); ApplyPermission(); ExecutionTime.Stop(ExecutionTimeTrackers.ApplyPermissions); if ((QueryType != RbacQueryTypes.Insert) && (QueryType != RbacQueryTypes.Delete)) { ExecutionTime.Start(ExecutionTimeTrackers.ApplyParameters); if (!ApplyParameters()) { RbacException.Raise(ParamErrors.ToLine()); } ExecutionTime.Stop(ExecutionTimeTrackers.ApplyParameters); } WriteLogParseDetails(); }
public RbacEntitlement(RbacRole role) { if (role == null) { RbacException.Raise("A valid role is required to create entitlements!"); } RbacEntitlement entitlement = FromXml(role.MetaDataEntitlements); if (entitlement != null) { this.Menus = entitlement.Menus; this.Screens = entitlement.Screens; } }
private void UpdateReferredTables(string tableName, string tableAlias) { RbacTable actualTable = Context.User.Role.CrudPermissions.Find(tableName); actualTable.Alias = tableAlias; if (actualTable != null) { TablesReferred.Add(actualTable); } else { RbacException.Raise(string.Format("The referred table {0} was not found in meta data!", tableName), RbacExceptionCategories.Parser); } }
private RbacCache() { //string passKey = RbacPassKey.GetPassKey(); //if (String.IsNullOrEmpty(passKey)) // RbacPassKey.CreatePassKey(Resources.PassKey); //passKey = RbacPassKey.GetPassKey(); string passKey = Resources.PassKey; if (String.IsNullOrEmpty(passKey)) { RbacException.Raise("Cannot retrieve pass key!"); } Password = UTF8Encoding.UTF8.GetBytes(passKey); Contexts = new Dictionary <string, Rbac>(); }
public RbacUser Authenticate(string userName, string password) { RbacUser user = GetUser(userName); if (user == null) { RbacException.Raise("User name was not found!"); } user = new DataManager.Manager().Authenticate(userName, password); if (user == null) { RbacException.Raise("Incorrect password!"); } return(user); }
public SelectColumnRemover(string query, RbacSelectColumn column) { Query = query; Column = column; int fromIndex = Query.IndexOf(" into", StringComparison.OrdinalIgnoreCase); if (fromIndex == -1) { fromIndex = Query.IndexOf("from", StringComparison.OrdinalIgnoreCase); } if (fromIndex == -1) { RbacException.Raise("Something went wrong while applying permission on select columns, no 'into' or 'from' statement found in the query"); } SelectStatement = Query.Substring(0, fromIndex); OtherStatement = " " + Query.Substring(fromIndex, Query.Length - fromIndex); }
/// <summary> /// Instantiates a new Rbac Role /// </summary> /// <param name="rbacId">The rbac id it will belong to</param> /// <param name="name">Name of the new role</param> /// <param name="description">Description of the new role</param> /// <param name="metaDataRbac">Meta data of the role</param> /// <param name="metaDataEntitlements">Meta data of the entilements</param> public RbacRole(int rbacId, string name, string description, string metaDataRbac, string metaDataEntitlements) { if (rbacId == 0) { RbacException.Raise("Creation of role requires a valid rbacId!"); } Rbac rbac = new Framework.Rbac(); //create new role RbacRole newRole = new RbacRole(); newRole.RbacId = rbacId; newRole.Name = name; newRole.Description = description; newRole.MetaDataRbac = metaDataRbac; newRole.MetaDataEntitlements = metaDataEntitlements; newRole = new DataManager.Manager(false).AddOrUpdate(newRole); Assign(newRole); }
public void ApplyPermissionSelect() { var tables = Columns.GroupBy(c => c.Table.Name).Select(grp => grp.ToList()).ToList(); foreach (var allColumnnsInATable in tables) { if (allColumnnsInATable.Count > 0) { //RbacTable rbacTable = TablesReferred.Find(allColumnnsInATable[0].Table.Name); //if (rbacTable == null) // throw new Exception("Could not find table name in referred tables!"); if (allColumnnsInATable[0].Table.AllowedOperations.HasFlag(RbacDBOperations.Read)) { foreach (RbacSelectColumn column in allColumnnsInATable) { RbacColumn rbacColumn = allColumnnsInATable[0].Table.FindColumn(column.Name); if (rbacColumn == null) { RbacException.Raise( string.Format("Role '{0}' belongs to '{1}' is not in sync with database. The column '{2}' of table '{3}' was not found in the role meta data", this.Context.User.UserName, this.Context.User.Role.Name, column.Name, column.Table.Name)); } if (!rbacColumn.AllowedOperations.HasFlag(RbacDBOperations.Read)) { RemoveColumnFromSelect(column); } } } else { //user do not have access to this table RemoveColumnFromSelect(allColumnnsInATable); } } } IsPermissionApplied = true; }
public Rbac CreateNew(string rbacName, string description, string connectionString, string metaDataEntitlement) { DataManager.Manager manager = new DataManager.Manager(false); if (manager.GetRbac(rbacName) != null) { RbacException.Raise(string.Format("'{0}' already exists! Please provide a different name.", rbacName), RbacExceptionCategories.Repository); } Rbac newRbac = new Rbac(); newRbac.Name = rbacName; newRbac.Description = description; newRbac.ConnectionString = connectionString; N("Generating meta data..."); newRbac.MetaDataRbac = RbacMetaData.Generate(newRbac.ConnectionString); N("Done!", LogMessageTypes.Success); N("Saving your rbac instance..."); Rbac rbac = manager.AddOrUpdate(newRbac); N("Done!", LogMessageTypes.Success); return(rbac); }
public override void ExplicitVisit(NamedTableReference node) { string tableName = node.SchemaObject.BaseIdentifier != null ? node.SchemaObject.BaseIdentifier.Value : string.Empty; string tableAlias = node.Alias != null ? node.Alias.Value : string.Empty; RbacTable table = Context.User.Role.CrudPermissions.Find(tableName); if (table == null) { table = Context.User.Role.CrudPermissions.Find(tableAlias); } if (table == null) { RbacException.Raise(string.Format("The referred table {0} was not found in meta data!", tableName), RbacExceptionCategories.Parser); } table.Alias = tableAlias; table.Server = node.SchemaObject.ServerIdentifier != null ? node.SchemaObject.ServerIdentifier.Value : string.Empty; table.Database = node.SchemaObject.DatabaseIdentifier != null ? node.SchemaObject.DatabaseIdentifier.Value : string.Empty; table.Schema = node.SchemaObject.SchemaIdentifier != null ? node.SchemaObject.SchemaIdentifier.Value : string.Empty; Tables.Add(table); }
private void ParseQueryType() { QueryType = RbacQueryTypes.Unknown; if ((OriginalQuery.Length >= 6) && (OriginalQuery.Substring(0, 6).ToLower() == "select")) { QueryType = RbacQueryTypes.Select; } else if ((OriginalQuery.Length >= 6) && (OriginalQuery.Substring(0, 6).ToLower() == "insert")) { QueryType = RbacQueryTypes.Insert; } else if ((OriginalQuery.Length >= 6) && (OriginalQuery.Substring(0, 6).ToLower() == "update")) { QueryType = RbacQueryTypes.Update; } else if ((OriginalQuery.Length >= 6) && (OriginalQuery.Substring(0, 6).ToLower() == "delete")) { QueryType = RbacQueryTypes.Delete; } else { RbacException.Raise("Invalid query type!"); } }
private void ParseSqlUpdateStatement(TSqlStatement sqlStatement) { if (sqlStatement.GetType() == typeof(UpdateStatement)) { UpdateStatement aUpdateStatement = (UpdateStatement)sqlStatement; #region Handle Target Table #endregion Handle Target Table RbacTable targetTable = new RbacTable(); #region Handle From Clause - When Update with Join if (aUpdateStatement.UpdateSpecification.FromClause != null) { //mostly update with join case NamedTableReferenceVisitor fromClauseNtVisitor = new NamedTableReferenceVisitor(Context); aUpdateStatement.UpdateSpecification.FromClause.AcceptChildren(fromClauseNtVisitor); this.TablesReferred = fromClauseNtVisitor.Tables; if (TablesReferred.Count > 0) { targetTable = TablesReferred[0]; //if alias is being updated, we need to fix table name RbacTable tryTable = Context.User.Role.CrudPermissions.Find(targetTable.Name); if (tryTable == null) { //alias is being updated, lets get the actual table name var tt = fromClauseNtVisitor.Tables.Where(t => t.Alias == targetTable.Name).ToList()[0]; if (tt != null) { targetTable.Name = tt.Name; } } } else { RbacException.Raise("No target table found in the update query!"); } } else { NamedTableReferenceVisitor ntVisitor = new NamedTableReferenceVisitor(Context); aUpdateStatement.UpdateSpecification.Target.Accept(ntVisitor); if (ntVisitor.Tables.Count == 0) { RbacException.Raise("No target table found in the update query!"); } else if (ntVisitor.Tables.Count == 1) { targetTable = ntVisitor.Tables[0]; } else { RbacException.Raise("More than 1 target tables found in the update query! Currently not supported."); } TablesReferred.Add(targetTable); } #endregion Handle From Clause - When Update with Join #region Handle Columns SetClauseVisitor scVisitor = new SetClauseVisitor(targetTable.Name); aUpdateStatement.UpdateSpecification.AcceptChildren(scVisitor); Columns = scVisitor.Columns; UpdateReferredTables(Columns); #endregion Handle Columns } else { Errors.Add("Not a update statement!"); } }
public string Generate(string connectionString, string fileName = null) { if (connectionString.IndexOf("MultipleActiveResultSets=true", StringComparison.OrdinalIgnoreCase) == -1) { if (connectionString.TrimEnd().Substring(connectionString.Length - 1, 1) != ";") { connectionString += ";"; } connectionString += "MultipleActiveResultSets=true"; } string xml = string.Empty; try { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); DataTable foreignKeys = GetForeignKeys(connection); SqlCommand tCommand = new SqlCommand("select object_id, name from sys.tables where name != 'sysdiagrams' order by name", connection); SqlDataReader tReader = tCommand.ExecuteReader(); XmlDocument doc = ValidateAndGetRbacXmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(xmlDeclaration); XmlElement root = doc.CreateElement("Rbac"); doc.AppendChild(root); XmlElement summary = doc.CreateElement("Summary"); XmlAttribute genOn = doc.CreateAttribute("GeneratedOn"); genOn.Value = DateTime.Now.ToString(); summary.Attributes.Append(genOn); XmlAttribute genBy = doc.CreateAttribute("GeneratedBy"); genBy.Value = "TODO"; summary.Attributes.Append(genBy); root.AppendChild(summary); XmlElement tablesNode = doc.CreateElement("Tables"); root.AppendChild(tablesNode); while (tReader.Read()) { XmlNode tableNode = doc.CreateElement("Table"); XmlAttribute Id = doc.CreateAttribute("Id"); Id.Value = tReader[0].ToString(); tableNode.Attributes.Append(Id); XmlAttribute Name = doc.CreateAttribute("Name"); Name.Value = tReader[1].ToString(); tableNode.Attributes.Append(Name); AddCRUDDefaults(doc, tableNode, true); SqlCommand cCommand = new SqlCommand( string.Format("select c.name, tp.name from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.types tp on tp.system_type_id = c.system_type_id where t.object_id = {0}" , Id.Value), connection); SqlDataReader cReader = cCommand.ExecuteReader(); string oneColumnName = string.Empty; XmlNode columnsNode = doc.CreateElement("Columns"); while (cReader.Read()) { XmlNode columnNode = doc.CreateElement("Column"); XmlAttribute cName = doc.CreateAttribute("Name"); cName.Value = cReader[0].ToString(); columnNode.Attributes.Append(cName); XmlAttribute type = doc.CreateAttribute("Type"); type.Value = cReader[1].ToString(); columnNode.Attributes.Append(type); AddCRUDDefaults(doc, columnNode, false); columnsNode.AppendChild(columnNode); oneColumnName = cName.Value; } cReader.Close(); tableNode.AppendChild(columnsNode); tableNode.AppendChild(GetForeignKeyNode(foreignKeys, Name.Value, doc)); tableNode.AppendChild(AddConditions(doc, oneColumnName)); tableNode.AppendChild(AddParameters(doc, oneColumnName)); tablesNode.AppendChild(tableNode); } doc.DocumentElement.SetAttribute("xmlns:xsd", "https://github.com/eyedia/aarbac"); if (!string.IsNullOrEmpty(fileName)) { doc.Save(fileName); } else { using (var stringWriter = new StringWriter()) using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { doc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); xml = stringWriter.GetStringBuilder().ToString(); ValidateAndGetRbacXmlDocument(xml); if (XmlValidationErrors.Count > 0) { RbacException.Raise("Cannot generate meta data, XML validation failed!" + Environment.NewLine + XmlValidationErrors.ToLine()); } } } tReader.Close(); connection.Close(); } } catch (ArgumentException ex) { RbacException.Raise("Failed, check your connection string and try again."); } return(xml); }
public override void ExplicitVisit(SelectStarExpression node) { string query = String.Join(string.Empty, node.ScriptTokenStream.Select(sts => sts.Text).ToArray()); string tableNameOrAlias = string.Empty; bool hasIdentifier = false; if (node.Qualifier != null) { tableNameOrAlias = node.Qualifier.Identifiers[0].Value; hasIdentifier = true; } else { int pos = node.ScriptTokenStream.Select((v, i) => new { token = v, index = i }).First(sts => sts.token.TokenType == TSqlTokenType.From).index; tableNameOrAlias = node.ScriptTokenStream[pos + 2].Text; if ((node.ScriptTokenStream.Count > (pos + 2 + 2)) && (node.ScriptTokenStream[pos + 4].TokenType == TSqlTokenType.Identifier)) { //e.g. 'select * from Author a' getting 'a' tableNameOrAlias = node.ScriptTokenStream[pos + 4].Text; } } bool isAlias = false; RbacTable table = Context.User.Role.CrudPermissions.Find(tableNameOrAlias, ref isAlias); if (table != null) { foreach (RbacColumn col in table.Columns) { RbacSelectColumn column = new RbacSelectColumn(); if (isAlias) { column.Table.Alias = tableNameOrAlias; column.Table.Name = table.Name; } else { column.Table.Name = tableNameOrAlias; } column.Table = table; column.Name = col.Name; Columns.Add(column); } if ((isAlias) && (hasIdentifier)) { ParsedQuery = query.Replace(tableNameOrAlias + ".*", table.Columns.ToCommaSeparatedString(tableNameOrAlias)); } else { ParsedQuery = query.Replace("*", table.Columns.ToCommaSeparatedString(tableNameOrAlias)); } } else { RbacException.Raise(string.Format("The referred table {0} was not found in meta data!", tableNameOrAlias), RbacExceptionCategories.Parser); } }