Exemplo n.º 1
0
 ///<summary>Inserts one SecurityLog into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(SecurityLog securityLog,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         securityLog.SecurityLogNum=ReplicationServers.GetKey("securitylog","SecurityLogNum");
     }
     string command="INSERT INTO securitylog (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="SecurityLogNum,";
     }
     command+="PermType,UserNum,LogDateTime,LogText,PatNum,CompName) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(securityLog.SecurityLogNum)+",";
     }
     command+=
              POut.Int   ((int)securityLog.PermType)+","
         +    POut.Long  (securityLog.UserNum)+","
         +    DbHelper.Now()+","
         +"'"+POut.String(securityLog.LogText)+"',"
         +    POut.Long  (securityLog.PatNum)+","
         +"'"+POut.String(securityLog.CompName)+"')";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         securityLog.SecurityLogNum=Db.NonQ(command,true);
     }
     return securityLog.SecurityLogNum;
 }
Exemplo n.º 2
0
 ///<summary>Inserts one SecurityLog into the database.  Returns the new priKey.</summary>
 internal static long Insert(SecurityLog securityLog)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         securityLog.SecurityLogNum=DbHelper.GetNextOracleKey("securitylog","SecurityLogNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(securityLog,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     securityLog.SecurityLogNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(securityLog,false);
     }
 }
Exemplo n.º 3
0
        ///<summary>Updates one SecurityLog in the database.</summary>
        internal static void Update(SecurityLog securityLog)
        {
            string command = "UPDATE securitylog SET "
                             + "PermType      =  " + POut.Int((int)securityLog.PermType) + ", "
                             + "UserNum       =  " + POut.Long(securityLog.UserNum) + ", "
                             //LogDateTime not allowed to change
                             + "LogText       = '" + POut.String(securityLog.LogText) + "', "
                             + "PatNum        =  " + POut.Long(securityLog.PatNum) + ", "
                             + "CompName      = '" + POut.String(securityLog.CompName) + "' "
                             + "WHERE SecurityLogNum = " + POut.Long(securityLog.SecurityLogNum);

            Db.NonQ(command);
        }
Exemplo n.º 4
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void setupAuthManager(org.neo4j.server.security.auth.AuthenticationStrategy authStrategy) throws Throwable
        private void SetupAuthManager(AuthenticationStrategy authStrategy)
        {
            FormattedLog.Builder builder = FormattedLog.withUTCTimeZone();
            _securityLogWriter = new StringWriter();
            Log log = builder.ToWriter(_securityLogWriter);

            _securityLog = new SecurityLog(log);
            InternalFlatFileRealm internalFlatFileRealm = new InternalFlatFileRealm(_users, new InMemoryRoleRepository(), new BasicPasswordPolicy(), authStrategy, mock(typeof(JobScheduler)), new InMemoryUserRepository(), new InMemoryUserRepository()
                                                                                    );

            _manager = new MultiRealmAuthManager(internalFlatFileRealm, Collections.singleton(internalFlatFileRealm), new MemoryConstrainedCacheManager(), _securityLog, true, false, Collections.emptyMap());
            _manager.init();
        }
Exemplo n.º 5
0
        private static void CredentialChanged(string keyName, string oldValue, string newValue)
        {
            switch (keyName)
            {
            case "SQLUser":
                SecurityLog.WriteToEventLogDB(null, SecurityAuditEvent.ProtecteDataUpdate, true, "EIDSS SQL login was changed", null, "SQL login was changed", SecurityAuditProcessType.Eidss);
                break;

            case "SQLPassword":
                SecurityLog.WriteToEventLogDB(null, SecurityAuditEvent.ProtecteDataUpdate, true, "EIDSS SQL login was changed", null, "SQL password was changed", SecurityAuditProcessType.Eidss);
                break;
            }
        }
Exemplo n.º 6
0
 ///<summary>Inserts one SecurityLog into the database.  Returns the new priKey.  Doesn't use the cache.</summary>
 public static long InsertNoCache(SecurityLog securityLog)
 {
     if (DataConnection.DBtype == DatabaseType.MySql)
     {
         return(InsertNoCache(securityLog, false));
     }
     else
     {
         if (DataConnection.DBtype == DatabaseType.Oracle)
         {
             securityLog.SecurityLogNum = DbHelper.GetNextOracleKey("securitylog", "SecurityLogNum");                  //Cacheless method
         }
         return(InsertNoCache(securityLog, true));
     }
 }
Exemplo n.º 7
0
 public LdapRealm(Config config, SecurityLog securityLog, SecureHasher secureHasher) : base()
 {
     this._securityLog  = securityLog;
     this._secureHasher = secureHasher;
     Name = SecuritySettings.LDAP_REALM_NAME;
     RolePermissionResolver = PredefinedRolesBuilder.RolePermissionResolver;
     ConfigureRealm(config);
     if (AuthenticationCachingEnabled)
     {
         CredentialsMatcher = secureHasher.HashedCredentialsMatcher;
     }
     else
     {
         CredentialsMatcher = new AllowAllCredentialsMatcher();
     }
 }
        /// <inheritdoc />
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var session = context.HttpContext.GetSession();

            if (session?.User == null)
            {
                SecurityLog.CreateRecord(
                    EnSecurityLogType.OperationDenied,
                    this.Severity,
                    context.HttpContext.GetRequestDescription(),
                    "Attempt to access {ControllerName} action {ActionName} without authenticated user",
                    (context.ActionDescriptor as ControllerActionDescriptor)?.ActionName,
                    (context.ActionDescriptor as ControllerActionDescriptor)?.ControllerName);
                context.Result = new StatusCodeResult(401);
            }
        }
Exemplo n.º 9
0
        internal MultiRealmAuthManager(EnterpriseUserManager userManager, ICollection <Realm> realms, CacheManager cacheManager, SecurityLog securityLog, bool logSuccessfulLogin, bool propertyAuthorization, IDictionary <string, IList <string> > roleToPropertyBlacklist)
        {
            this._userManager  = userManager;
            this._realms       = realms;
            this._cacheManager = cacheManager;

            _securityManager                = new DefaultSecurityManager(realms);
            this._securityLog               = securityLog;
            this._logSuccessfulLogin        = logSuccessfulLogin;
            this._propertyAuthorization     = propertyAuthorization;
            this._roleToPropertyBlacklist   = roleToPropertyBlacklist;
            _securityManager.SubjectFactory = new ShiroSubjectFactory();
            (( ModularRealmAuthenticator )_securityManager.Authenticator).AuthenticationStrategy = new ShiroAuthenticationStrategy();

            _securityManager.SubjectDAO = CreateSubjectDAO();
        }
Exemplo n.º 10
0
        ///<summary>Inserts one SecurityLog into the database.  Provides option to use the existing priKey.  Doesn't use the cache.</summary>
        public static long InsertNoCache(SecurityLog securityLog, bool useExistingPK)
        {
            bool   isRandomKeys = Prefs.GetBoolNoCache(PrefName.RandomPrimaryKeys);
            string command      = "INSERT INTO securitylog (";

            if (!useExistingPK && isRandomKeys)
            {
                securityLog.SecurityLogNum = ReplicationServers.GetKeyNoCache("securitylog", "SecurityLogNum");
            }
            if (isRandomKeys || useExistingPK)
            {
                command += "SecurityLogNum,";
            }
            command += "PermType,UserNum,LogDateTime,LogText,PatNum,CompName,FKey,LogSource,DefNum,DefNumError,DateTPrevious) VALUES(";
            if (isRandomKeys || useExistingPK)
            {
                command += POut.Long(securityLog.SecurityLogNum) + ",";
            }
            command +=
                POut.Int((int)securityLog.PermType) + ","
                + POut.Long(securityLog.UserNum) + ","
                + DbHelper.Now() + ","
                + DbHelper.ParamChar + "paramLogText,"
                + POut.Long(securityLog.PatNum) + ","
                + "'" + POut.String(securityLog.CompName) + "',"
                + POut.Long(securityLog.FKey) + ","
                + POut.Int((int)securityLog.LogSource) + ","
                + POut.Long(securityLog.DefNum) + ","
                + POut.Long(securityLog.DefNumError) + ","
                + POut.DateT(securityLog.DateTPrevious) + ")";
            if (securityLog.LogText == null)
            {
                securityLog.LogText = "";
            }
            OdSqlParameter paramLogText = new OdSqlParameter("paramLogText", OdDbType.Text, POut.StringParam(securityLog.LogText));

            if (useExistingPK || isRandomKeys)
            {
                Db.NonQ(command, paramLogText);
            }
            else
            {
                securityLog.SecurityLogNum = Db.NonQ(command, true, "SecurityLogNum", "securityLog", paramLogText);
            }
            return(securityLog.SecurityLogNum);
        }
        public async Task <IActionResult> Welcome(string loyaltyNumber)
        {
            if (!int.TryParse(loyaltyNumber, out var loyaltyNum))
            {
                SecurityLog.Warning("Invalid input from user!  {UserInput}", loyaltyNumber);
                //Log.Warning("Invalid input from user!  {UserInput}", loyaltyNumber);
                throw new Exception("Invalid input detected!!!");
            }
            var customer = await repo.GetCustomerByLoyaltyNumber(loyaltyNum);

            if (customer == null)
            {
                ModelState.AddModelError(string.Empty, "Unknown loyalty number");
                return(View());
            }
            return(RedirectToAction("LoyaltyOverview", new { loyaltyNumber }));
        }
Exemplo n.º 12
0
		///<summary>Converts a DataTable to a list of objects.</summary>
		public static List<SecurityLog> TableToList(DataTable table){
			List<SecurityLog> retVal=new List<SecurityLog>();
			SecurityLog securityLog;
			for(int i=0;i<table.Rows.Count;i++) {
				securityLog=new SecurityLog();
				securityLog.SecurityLogNum= PIn.Long  (table.Rows[i]["SecurityLogNum"].ToString());
				securityLog.PermType      = (Permissions)PIn.Int(table.Rows[i]["PermType"].ToString());
				securityLog.UserNum       = PIn.Long  (table.Rows[i]["UserNum"].ToString());
				securityLog.LogDateTime   = PIn.DateT (table.Rows[i]["LogDateTime"].ToString());
				securityLog.LogText       = PIn.String(table.Rows[i]["LogText"].ToString());
				securityLog.PatNum        = PIn.Long  (table.Rows[i]["PatNum"].ToString());
				securityLog.CompName      = PIn.String(table.Rows[i]["CompName"].ToString());
				securityLog.FKey          = PIn.Long  (table.Rows[i]["FKey"].ToString());
				retVal.Add(securityLog);
			}
			return retVal;
		}
Exemplo n.º 13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setUp() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SetUp()
        {
            _log = new AssertableLogProvider();
            SecurityLog securityLog = new SecurityLog(_log.getLog(this.GetType()));

            AuthProcedures             = new TestUserManagementProcedures();
            AuthProcedures.graph       = mock(typeof(GraphDatabaseAPI));
            AuthProcedures.securityLog = securityLog;

            _generalUserManager = UserManager;
            EnterpriseSecurityContext adminContext = new EnterpriseSecurityContext(new MockAuthSubject("admin"), [email protected]_Static.Full, Collections.emptySet(), true);

            _matsContext = new EnterpriseSecurityContext(new MockAuthSubject("mats"), [email protected]_Static.None, Collections.emptySet(), false);

            Subject = adminContext;
            _log.clear();
        }
Exemplo n.º 14
0
 ///<summary>Returns true if Update(SecurityLog,SecurityLog) would make changes to the database.
 ///Does not make any changes to the database and can be called before remoting role is checked.</summary>
 public static bool UpdateComparison(SecurityLog securityLog, SecurityLog oldSecurityLog)
 {
     if (securityLog.PermType != oldSecurityLog.PermType)
     {
         return(true);
     }
     if (securityLog.UserNum != oldSecurityLog.UserNum)
     {
         return(true);
     }
     //LogDateTime not allowed to change
     if (securityLog.LogText != oldSecurityLog.LogText)
     {
         return(true);
     }
     if (securityLog.PatNum != oldSecurityLog.PatNum)
     {
         return(true);
     }
     if (securityLog.CompName != oldSecurityLog.CompName)
     {
         return(true);
     }
     if (securityLog.FKey != oldSecurityLog.FKey)
     {
         return(true);
     }
     if (securityLog.LogSource != oldSecurityLog.LogSource)
     {
         return(true);
     }
     if (securityLog.DefNum != oldSecurityLog.DefNum)
     {
         return(true);
     }
     if (securityLog.DefNumError != oldSecurityLog.DefNumError)
     {
         return(true);
     }
     if (securityLog.DateTPrevious != oldSecurityLog.DateTPrevious)
     {
         return(true);
     }
     return(false);
 }
Exemplo n.º 15
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setup() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void Setup()
        {
            SecurityLog           securityLog           = mock(typeof(SecurityLog));
            InternalFlatFileRealm internalFlatFileRealm = new InternalFlatFileRealm(new InMemoryUserRepository(), new InMemoryRoleRepository(), new BasicPasswordPolicy(), new RateLimitedAuthenticationStrategy(Clock.systemUTC(), Config.defaults()), mock(typeof(JobScheduler)), new InMemoryUserRepository(), new InMemoryUserRepository()
                                                                                    );

            _testRealm = new TestRealm(this, LdapConfig, securityLog, new SecureHasher());

            IList <Realm> realms = listOf(internalFlatFileRealm, _testRealm);

            _fakeTicker  = new FakeTicker();
            _authManager = new MultiRealmAuthManager(internalFlatFileRealm, realms, new ShiroCaffeineCache.Manager(_fakeTicker.read, 100, 10, true), securityLog, false, false, Collections.emptyMap());
            _authManager.init();
            _authManager.start();

            _authManager.UserManager.newUser("mike", password("123"), false);
            _authManager.UserManager.newUser("mats", password("456"), false);
        }
Exemplo n.º 16
0
        public virtual async Task <IActionResult> GetList(int count = 100, int skip = 0)
        {
            var collectionRequest = new CollectionRequest <TObject>
            {
                Filter         = this.DefaultFilter,
                Sort           = this.DefaultSort,
                Count          = count,
                Skip           = skip,
                RequestContext =
                    this.GetRequestDescription()
            };

            CollectionResponse <TObject> response;

            if (this.DataListIsLarge || DataIsLarge)
            {
                collectionRequest.AcceptAsParcel = true;
                var notification =
                    await this.System.ActorSelection(this.GetDbActorProxyPath())
                    .Ask <ParcelNotification>(collectionRequest, this.AkkaTimeout);

                response = (CollectionResponse <TObject>) await notification.Receive(this.System);
            }
            else
            {
                collectionRequest.AcceptAsParcel = false;
                response =
                    await this.System.ActorSelection(this.GetDbActorProxyPath())
                    .Ask <CollectionResponse <TObject> >(collectionRequest, this.AkkaTimeout);
            }

            var severity = typeof(TObject).GetInterfaces().Any(i => i == typeof(ICrucialObject))
                                 ? EnSeverity.Crucial
                                 : EnSeverity.Trivial;

            SecurityLog.CreateRecord(
                EnSecurityLogType.DataReadGranted,
                severity,
                this.GetRequestDescription(),
                "The list of {ObjectType} was read.",
                typeof(TObject).FullName);

            return(this.Ok(response));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Sets the operation log
        /// </summary>
        /// <param name="request">
        /// The initial request
        /// </param>
        /// <param name="apiField">
        /// The connection field
        /// </param>
        /// <param name="context">
        /// The request context
        /// </param>
        /// <param name="action">
        /// The action performed
        /// </param>
        protected static void SetLog(
            ApiRequest request,
            ApiField apiField,
            RequestContext context,
            EnConnectionAction action)
        {
            if (apiField.LogAccessRules == null || !apiField.LogAccessRules.Any())
            {
                return;
            }

            var rule =
                apiField.LogAccessRules.OrderByDescending(r => r.Severity)
                .FirstOrDefault(r => r.ConnectionActions.HasFlag(action));

            if (rule == null)
            {
                return;
            }

            var operationGranted = EnSecurityLogType.OperationGranted;

            switch (action)
            {
            case EnConnectionAction.Create:
                operationGranted = EnSecurityLogType.DataCreateGranted;
                break;

            case EnConnectionAction.Update:
                operationGranted = EnSecurityLogType.DataUpdateGranted;
                break;

            case EnConnectionAction.Delete:
                operationGranted = EnSecurityLogType.DataDeleteGranted;
                break;
            }

            SecurityLog.CreateRecord(
                operationGranted,
                rule.Severity,
                context,
                rule.LogMessage,
                ((JObject)request.Arguments).ToString(Formatting.None));
        }
Exemplo n.º 18
0
    protected void ReloadData()
    {
        if (!SecurityHelper.DebugSecurity)
        {
            ShowWarning(GetString("DebugSecurity.NotConfigured"), null, null);
        }
        else
        {
            plcLogs.Controls.Clear();

            for (int i = SecurityHelper.LastLogs.Count - 1; i >= 0; i--)
            {
                try
                {
                    // Get the log
                    RequestLog log = (RequestLog)SecurityHelper.LastLogs[i];
                    if (log != null)
                    {
                        // Load the table
                        DataTable dt = log.LogTable;
                        if (!DataHelper.DataSourceIsEmpty(dt))
                        {
                            // Log the control
                            SecurityLog logCtrl = (SecurityLog)LoadUserControl("~/CMSAdminControls/Debug/SecurityLog.ascx");
                            logCtrl.ID = "logSec_" + i;
                            logCtrl.EnableViewState     = false;
                            logCtrl.Log                 = log;
                            logCtrl.DisplayHeader       = false;
                            logCtrl.ShowCompleteContext = chkCompleteContext.Checked;

                            // Add to the output
                            plcLogs.Controls.Add(new LiteralControl("<div>&lrm;<strong>&nbsp;" + GetRequestLink(log.RequestURL, log.RequestGUID) + "</strong> (" + log.RequestTime.ToString("hh:mm:ss") + ")&lrm;<br /><br />"));
                            plcLogs.Controls.Add(logCtrl);
                            plcLogs.Controls.Add(new LiteralControl("</div><br /><br />"));
                        }
                    }
                }
                catch //(Exception ex)
                {
                }
            }
        }
    }
Exemplo n.º 19
0
        ///<summary>Converts a DataTable to a list of objects.</summary>
        internal static List <SecurityLog> TableToList(DataTable table)
        {
            List <SecurityLog> retVal = new List <SecurityLog>();
            SecurityLog        securityLog;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                securityLog = new SecurityLog();
                securityLog.SecurityLogNum = PIn.Long(table.Rows[i]["SecurityLogNum"].ToString());
                securityLog.PermType       = (Permissions)PIn.Int(table.Rows[i]["PermType"].ToString());
                securityLog.UserNum        = PIn.Long(table.Rows[i]["UserNum"].ToString());
                securityLog.LogDateTime    = PIn.DateT(table.Rows[i]["LogDateTime"].ToString());
                securityLog.LogText        = PIn.String(table.Rows[i]["LogText"].ToString());
                securityLog.PatNum         = PIn.Long(table.Rows[i]["PatNum"].ToString());
                securityLog.CompName       = PIn.String(table.Rows[i]["CompName"].ToString());
                retVal.Add(securityLog);
            }
            return(retVal);
        }
        public async Task <IActionResult> LoyaltyOverview(int loyaltyNumber)
        {
            ViewBag.Title = "Your points";
            var userLoyaltyNumber = int.Parse(User.Claims.FirstOrDefault(a => a.Type == "loyalty")?.Value ?? "0");

            if (userLoyaltyNumber != loyaltyNumber)
            {
                SecurityLog.Warning("Unauthorized access attempted on {LoyaltyNum}", loyaltyNumber);
                //Log.Warning("Unauthorized access attempted on {LoyaltyNum}", loyaltyNumber);
                throw new Exception($"Unauthorized to see loyalty number {loyaltyNumber}!!");
            }
            var customer = await repo.GetCustomerByLoyaltyNumber(loyaltyNumber);

            var pointsNeeded = int.Parse(config["CustomerPortalSettings:PointsNeeded"]);

            var loyaltyModel = LoyaltyModel.FromCustomer(customer, pointsNeeded);

            return(View(loyaltyModel));
        }
Exemplo n.º 21
0
        public virtual async Task <IActionResult> Get(TId id)
        {
            var request = new CrudActionMessage <TObject, TId>
            {
                ActionType     = EnActionType.Get,
                Id             = id,
                RequestContext =
                    this.GetRequestDescription()
            };
            var response = await this.SendRequest(request);

            SecurityLog.CreateRecord(
                EnSecurityLogType.DataReadGranted,
                response is ICrucialObject ? EnSeverity.Crucial : EnSeverity.Trivial,
                this.GetRequestDescription(),
                "{ObjectType} with id {ObjectId} was read.",
                typeof(TObject).FullName,
                id);

            return(this.Ok(response));
        }
Exemplo n.º 22
0
 public static void LogSecurityAction(HttpRequest request, NTGPrincipal user, string action, NTGDBTransactional transaction = null)
 {
     try
     {
         var log = new SecurityLog
         {
             Browser   = request.UserAgent,
             Date      = DateTime.UtcNow,
             IPAddress = request.UserHostAddress,
             Action    = action,
             UserId    = user.Id,
             UserEmail = user.Email,
             UserType  = string.Join(",", user.Roles)
         };
         log.Save(transaction);
     }
     catch (Exception ex)
     {
         LogError(request, ex);
     }
 }
Exemplo n.º 23
0
 public static void LogSecurityAction(HttpRequest request, string action, int?userId, string userEmail, string userType, NTGDBTransactional transaction = null)
 {
     try
     {
         var log = new SecurityLog
         {
             Browser   = request.UserAgent,
             Date      = DateTime.UtcNow,
             IPAddress = request.UserHostAddress,
             Action    = action,
             UserId    = userId,
             UserEmail = userEmail,
             UserType  = userType
         };
         log.Save(transaction);
     }
     catch (Exception ex)
     {
         LogError(request, ex);
     }
 }
Exemplo n.º 24
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void setup(Dependencies dependencies) throws org.neo4j.internal.kernel.api.exceptions.KernelException
        public override void Setup(Dependencies dependencies)
        {
            Config                config           = dependencies.Config();
            Procedures            procedures       = dependencies.Procedures();
            LogProvider           logProvider      = dependencies.LogService().UserLogProvider;
            JobScheduler          jobScheduler     = dependencies.Scheduler();
            FileSystemAbstraction fileSystem       = dependencies.FileSystem();
            AccessCapability      accessCapability = dependencies.AccessCapability();

            SecurityLog securityLog = SecurityLog.create(config, dependencies.LogService().getInternalLog(typeof(GraphDatabaseFacade)), fileSystem, jobScheduler);

            Life.add(securityLog);

            _authManager = NewAuthManager(config, logProvider, securityLog, fileSystem, jobScheduler, accessCapability);
            Life.add(dependencies.DependencySatisfier().satisfyDependency(_authManager));

            // Register procedures
            procedures.RegisterComponent(typeof(SecurityLog), ctx => securityLog, false);
            procedures.RegisterComponent(typeof(EnterpriseAuthManager), ctx => _authManager, false);
            procedures.RegisterComponent(typeof(EnterpriseSecurityContext), ctx => AsEnterprise(ctx.get(SECURITY_CONTEXT)), true);

            if (SecurityConfig.nativeAuthEnabled)
            {
                procedures.RegisterComponent(typeof(EnterpriseUserManager), ctx => _authManager.getUserManager(ctx.get(SECURITY_CONTEXT).subject(), ctx.get(SECURITY_CONTEXT).Admin), true);
                if (config.Get(SecuritySettings.auth_providers).Count > 1)
                {
                    procedures.RegisterProcedure(typeof(UserManagementProcedures), true, "%s only applies to native users.");
                }
                else
                {
                    procedures.RegisterProcedure(typeof(UserManagementProcedures), true);
                }
            }
            else
            {
                procedures.RegisterComponent(typeof(EnterpriseUserManager), ctx => EnterpriseUserManager.NOOP, true);
            }

            procedures.RegisterProcedure(typeof(SecurityProcedures), true);
        }
Exemplo n.º 25
0
        /*
         * Logging scenario smoke test
         */
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldLogSecurityEvents() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldLogSecurityEvents()
        {
            S mats = Neo.login("mats", "neo4j");

            // for REST, login doesn't happen until the subject does something
            Neo.executeQuery(mats, "UNWIND [] AS i RETURN 1", Collections.emptyMap(), r =>
            {
            });
            AssertEmpty(AdminSubject, "CALL dbms.security.createUser('mats', 'neo4j', false)");
            AssertEmpty(AdminSubject, "CALL dbms.security.createRole('role1')");
            AssertEmpty(AdminSubject, "CALL dbms.security.deleteRole('role1')");
            AssertEmpty(AdminSubject, "CALL dbms.security.addRoleToUser('reader', 'mats')");
            mats = Neo.login("mats", "neo4j");
            AssertEmpty(mats, "MATCH (n) WHERE id(n) < 0 RETURN 1");
            AssertFail(mats, "CALL dbms.security.changeUserPassword('neo4j', 'hackerPassword')", PERMISSION_DENIED);
            AssertFail(mats, "CALL dbms.security.changeUserPassword('mats', '')", "A password cannot be empty.");
            AssertEmpty(mats, "CALL dbms.security.changeUserPassword('mats', 'hackerPassword')");
            AssertEmpty(AdminSubject, "CALL dbms.security.removeRoleFromUser('reader', 'mats')");
            AssertEmpty(AdminSubject, "CALL dbms.security.deleteUser('mats')");

            // flush log
            Neo.LocalGraph.shutdown();

            // assert on log content
            SecurityLog log = new SecurityLog(this);

            log.Load();

            log.AssertHasLine("mats", "failed to log in");
            log.AssertHasLine("adminSubject", "created user `mats`");
            log.AssertHasLine("adminSubject", "created role `role1`");
            log.AssertHasLine("adminSubject", "deleted role `role1`");
            log.AssertHasLine("mats", "logged in");
            log.AssertHasLine("adminSubject", "added role `reader` to user `mats`");
            log.AssertHasLine("mats", "tried to change password for user `neo4j`: " + PERMISSION_DENIED);
            log.AssertHasLine("mats", "tried to change password: A password cannot be empty.");
            log.AssertHasLine("mats", "changed password");
            log.AssertHasLine("adminSubject", "removed role `reader` from user `mats`");
            log.AssertHasLine("adminSubject", "deleted user `mats`");
        }
Exemplo n.º 26
0
        ///<summary></summary>
        public static void Insert(SecurityLog log)
        {
            if (PrefB.RandomKeys)
            {
                log.SecurityLogNum = MiscData.GetKey("securitylog", "SecurityLogNum");
            }
            string command = "INSERT INTO securitylog (";

            if (PrefB.RandomKeys)
            {
                command += "SecurityLogNum,";
            }
            command += "PermType,UserNum,LogDateTime,LogText,PatNum) VALUES(";
            if (PrefB.RandomKeys)
            {
                command += "'" + POut.PInt(log.SecurityLogNum) + "', ";
            }
            command +=
                "'" + POut.PInt((int)log.PermType) + "', "
                + "'" + POut.PInt(log.UserNum) + "', ";
            if (FormChooseDatabase.DBtype == DatabaseType.Oracle)
            {
                command += POut.PDateT(MiscData.GetNowDateTime());
            }
            else              //Assume MySQL
            {
                command += "NOW()";
            }
            command += ", "          //LogDateTime set to current server time
                       + "'" + POut.PString(log.LogText) + "', "
                       + "'" + POut.PInt(log.PatNum) + "')";
            if (PrefB.RandomKeys)
            {
                General.NonQ(command);
            }
            else
            {
                log.SecurityLogNum = General.NonQ(command, true);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Process the <see cref="ConfigurationSetObsoleteRequest"/>
        /// </summary>
        /// <param name="request">The request</param>
        private void OnConfigurationSetObsolete(ConfigurationSetObsoleteRequest request)
        {
            try
            {
                using (var ds = this.GetContext())
                {
                    var configuration = ds.Configurations.FirstOrDefault(r => r.Id == request.Id);
                    if (configuration == null)
                    {
                        this.Sender.Tell(CrudActionResponse <Configuration> .Error(new EntityNotFoundException(), null));
                        return;
                    }

                    if (configuration.State != EnConfigurationState.Ready)
                    {
                        this.Sender.Tell(
                            CrudActionResponse <Configuration> .Error(
                                new Exception("Only ready configurations can be made obsolete manually"),
                                null));
                        return;
                    }

                    configuration.State = EnConfigurationState.Obsolete;
                    ds.SaveChanges();
                    this.Sender.Tell(CrudActionResponse <Configuration> .Success(configuration, null));
                    SecurityLog.CreateRecord(
                        EnSecurityLogType.OperationGranted,
                        EnSeverity.Crucial,
                        request.Context,
                        "Configuration {ConfigurationId} marked as obsolete",
                        configuration.Id);
                }
            }
            catch (Exception exception)
            {
                this.Sender.Tell(CrudActionResponse <Configuration> .Error(exception, null));
            }
        }
Exemplo n.º 28
0
        public static void ExitApp(bool forceExit)
        {
            //delete record from journal
            if (!(m_WasExit) && BaseFormManager.MainForm != null)
            {
                ((MainForm)BaseFormManager.MainForm).UpdateMessenger.DeleteRunningApps(ModelUserContext.ClientID, AppCode);
            }

            //SecurityLog.WriteToEventLogWindows(BvMessages.Get("SecurityLog_EIDSS_finished_successfully"), , EventLogEntryType.Information)
            if (!(m_WasExit))
            {
                SecurityLog.WriteToEventLogDB(EidssUserContext.User.ID, SecurityAuditEvent.ProcessStop, true,
                                              "EIDSS is stopped", null, "EIDSS is stopped",
                                              SecurityAuditProcessType.Eidss);
                m_WasExit = true;
            }

            m_AskForExit = false;
            if (forceExit)
            {
                Application.Exit();
            }
        }
Exemplo n.º 29
0
    public List <string> GetOfficerList(SecurityCoreContext _context, SecurityLog secLog, int rowID, List <string> OfficerIDs)
    {
        int CurrentID     = secLog.ID;
        var SecLogOfficer = _context.SecurityLogOfficer.ToList();
        var Officer       = _context.Officer.ToList();

        int count = SecLogOfficer.Where(slo => slo.SecurityLogID == CurrentID).Count();

        if (count >= 0)
        {
            OfficerIDs.Add("");
        }
        foreach (secLog slo in SecLogOfficer.Where(slo => slo.SecurityLogID == CurrentID))
        {
            OfficerIDs[rowID] = OfficerIDs[rowID] + slo.Officer.FullName + ", ";
        }
        if (count > 0)
        {
            OfficerIDs[rowID] = OfficerIDs[rowID].Substring(0, OfficerIDs[rowID].Length - 2);
        }

        return(OfficerIDs);
    }
Exemplo n.º 30
0
        ///<summary>Updates one SecurityLog in the database.</summary>
        public static void Update(SecurityLog securityLog)
        {
            string command = "UPDATE securitylog SET "
                             + "PermType      =  " + POut.Int((int)securityLog.PermType) + ", "
                             + "UserNum       =  " + POut.Long(securityLog.UserNum) + ", "
                             //LogDateTime not allowed to change
                             + "LogText       =  " + DbHelper.ParamChar + "paramLogText, "
                             + "PatNum        =  " + POut.Long(securityLog.PatNum) + ", "
                             + "CompName      = '" + POut.String(securityLog.CompName) + "', "
                             + "FKey          =  " + POut.Long(securityLog.FKey) + ", "
                             + "LogSource     =  " + POut.Int((int)securityLog.LogSource) + ", "
                             + "DefNum        =  " + POut.Long(securityLog.DefNum) + ", "
                             + "DefNumError   =  " + POut.Long(securityLog.DefNumError) + ", "
                             + "DateTPrevious =  " + POut.DateT(securityLog.DateTPrevious) + " "
                             + "WHERE SecurityLogNum = " + POut.Long(securityLog.SecurityLogNum);

            if (securityLog.LogText == null)
            {
                securityLog.LogText = "";
            }
            OdSqlParameter paramLogText = new OdSqlParameter("paramLogText", OdDbType.Text, POut.StringParam(securityLog.LogText));

            Db.NonQ(command, paramLogText);
        }
Exemplo n.º 31
0
        ///<summary>Converts a DataTable to a list of objects.</summary>
        public static List <SecurityLog> TableToList(DataTable table)
        {
            List <SecurityLog> retVal = new List <SecurityLog>();
            SecurityLog        securityLog;

            foreach (DataRow row in table.Rows)
            {
                securityLog = new SecurityLog();
                securityLog.SecurityLogNum = PIn.Long(row["SecurityLogNum"].ToString());
                securityLog.PermType       = (OpenDentBusiness.Permissions)PIn.Int(row["PermType"].ToString());
                securityLog.UserNum        = PIn.Long(row["UserNum"].ToString());
                securityLog.LogDateTime    = PIn.DateT(row["LogDateTime"].ToString());
                securityLog.LogText        = PIn.String(row["LogText"].ToString());
                securityLog.PatNum         = PIn.Long(row["PatNum"].ToString());
                securityLog.CompName       = PIn.String(row["CompName"].ToString());
                securityLog.FKey           = PIn.Long(row["FKey"].ToString());
                securityLog.LogSource      = (OpenDentBusiness.LogSources)PIn.Int(row["LogSource"].ToString());
                securityLog.DefNum         = PIn.Long(row["DefNum"].ToString());
                securityLog.DefNumError    = PIn.Long(row["DefNumError"].ToString());
                securityLog.DateTPrevious  = PIn.DateT(row["DateTPrevious"].ToString());
                retVal.Add(securityLog);
            }
            return(retVal);
        }
Exemplo n.º 32
0
            /// <summary>
            /// Creates an api requests to gather all data
            /// </summary>
            /// <param name="context">
            /// The request contexts
            /// </param>
            /// <param name="requestContext">
            /// The request Context.
            /// </param>
            /// <param name="responseType">response type</param>
            /// <returns>
            /// The request data
            /// </returns>
            private async Task <JObject> DoConnectionMutationApiRequests(
                ResolveFieldContext context,
                RequestContext requestContext,
                MergedConnectionMutationResultType responseType)
            {
                var arguments = context.FieldAst.Arguments.ToJson(context).Property("input")?.Value as JObject;

                var actionName = this.mergedField.FieldName?.Split('.').LastOrDefault();
                EnConnectionAction action;
                var originalApiField = this.mergedField.OriginalFields.Values.FirstOrDefault();

                if (Enum.TryParse(actionName, true, out action) && originalApiField != null &&
                    !originalApiField.CheckAuthorization(requestContext, action))
                {
                    var severity = originalApiField.LogAccessRules.Any()
                                       ? originalApiField.LogAccessRules.Max(l => l.Severity)
                                       : EnSeverity.Trivial;

                    SecurityLog.CreateRecord(
                        EnSecurityLogType.OperationDenied,
                        severity,
                        context.UserContext as RequestContext,
                        "Unauthorized call to {ApiPath}",
                        context.FieldAst.Name);

                    var emptyResponse = new JObject
                    {
                        {
                            "clientMutationId",
                            arguments?.Property("clientMutationId")?.ToObject <string>()
                        }
                    };
                    return(emptyResponse);
                }

                var edgeType            = responseType.EdgeType;
                var nodeType            = responseType.EdgeType.ObjectType;
                var requestedFields     = new List <ApiRequest>();
                var idSubRequestRequest = new List <ApiRequest>
                {
                    new ApiRequest
                    {
                        FieldName =
                            nodeType.KeyField.FieldName,
                        Alias = "__id"
                    }
                };
                var idRequestRequest = new ApiRequest
                {
                    Alias     = "__idRequest",
                    FieldName = "result",
                    Fields    = idSubRequestRequest
                };

                requestedFields.Add(idRequestRequest);

                var topFields =
                    GetRequestedFields(context.FieldAst.SelectionSet, context, this.mergedField.Type).ToList();

                var nodeRequests = topFields.Where(f => f.Name == "node" || f.Name == "edge").ToList();

                foreach (var nodeRequest in nodeRequests)
                {
                    var nodeAlias = nodeRequest.Alias ?? nodeRequest.Name;
                    switch (nodeRequest.Name)
                    {
                    case "node":
                        var nodeFields = nodeType.GatherSingleApiRequest(nodeRequest, context).ToList();
                        nodeFields.Add(new ApiRequest {
                            Alias = "__id", FieldName = nodeType.KeyField.FieldName
                        });
                        requestedFields.Add(
                            new ApiRequest {
                            Alias = nodeAlias, FieldName = "result", Fields = nodeFields
                        });
                        break;

                    case "edge":
                        var edgeFields = new List <ApiRequest>();
                        foreach (var edgeNodeRequests in
                                 GetRequestedFields(nodeRequest.SelectionSet, context, edgeType)
                                 .Where(f => f.Name == "node"))
                        {
                            edgeFields.AddRange(
                                nodeType.GatherSingleApiRequest(edgeNodeRequests, context).Select(
                                    f =>
                            {
                                f.Alias =
                                    $"{edgeNodeRequests.Alias ?? edgeNodeRequests.Name}_{f.Alias ?? f.FieldName}";
                                return(f);
                            }));
                        }

                        edgeFields.Add(new ApiRequest {
                            Alias = "__id", FieldName = nodeType.KeyField.FieldName
                        });
                        requestedFields.Add(
                            new ApiRequest {
                            Alias = nodeAlias, FieldName = "result", Fields = edgeFields
                        });

                        break;
                    }
                }

                if (responseType.ErrorType != null)
                {
                    var errorsRequest = topFields.Where(f => f.Name == "errors");
                    foreach (var field in errorsRequest)
                    {
                        requestedFields.Add(
                            new ApiRequest
                        {
                            FieldName = "errors",
                            Alias     = field.Alias,
                            Fields    =
                                responseType.ErrorType.GatherSingleApiRequest(field, context)
                                .ToList()
                        });
                    }
                }

                var request = new MutationApiRequest
                {
                    Arguments = arguments,
                    FieldName = this.mergedField.FieldName,
                    Fields    = requestedFields
                };

                var data = await this.provider.GetData(new List <ApiRequest> {
                    request
                }, requestContext);

                if (data != null)
                {
                    var mutation = (ApiMutation)this.mergedField.OriginalFields[this.provider.Description.ApiName];
                    var treePath = mutation.Path.Take(mutation.Path.Count - 1).ToList();

                    var parentGlobalId = new JArray(treePath.Select(r => new JObject {
                        { "f", r.FieldName }
                    }));
                    data.Add(GlobalIdPropertyName, parentGlobalId);

                    var elementRequest = mutation.Path.LastOrDefault();
                    if (elementRequest != null)
                    {
                        var localRequest = new JObject {
                            { "f", elementRequest.FieldName }
                        };
                        data.Add(RequestPropertyName, localRequest);
                    }
                }

                data?.Add("clientMutationId", arguments?.Property("clientMutationId")?.ToObject <string>());
                return(data);
            }
Exemplo n.º 33
0
 public SecurityLog InsertSecurityLog(SecurityLog entity)
 {
     return(_iSecurityLogRepository.InsertSecurityLog(entity));
 }
Exemplo n.º 34
0
		///<summary>Updates one SecurityLog in the database.</summary>
		public static void Update(SecurityLog securityLog){
			string command="UPDATE securitylog SET "
				+"PermType      =  "+POut.Int   ((int)securityLog.PermType)+", "
				+"UserNum       =  "+POut.Long  (securityLog.UserNum)+", "
				//LogDateTime not allowed to change
				+"LogText       = '"+POut.String(securityLog.LogText)+"', "
				+"PatNum        =  "+POut.Long  (securityLog.PatNum)+", "
				+"CompName      = '"+POut.String(securityLog.CompName)+"', "
				+"FKey          =  "+POut.Long  (securityLog.FKey)+", "
				+"LogSource     =  "+POut.Int   ((int)securityLog.LogSource)+" "
				+"WHERE SecurityLogNum = "+POut.Long(securityLog.SecurityLogNum);
			Db.NonQ(command);
		}
Exemplo n.º 35
0
		///<summary>Updates one SecurityLog in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.  Returns true if an update occurred.</summary>
		public static bool Update(SecurityLog securityLog,SecurityLog oldSecurityLog){
			string command="";
			if(securityLog.PermType != oldSecurityLog.PermType) {
				if(command!=""){ command+=",";}
				command+="PermType = "+POut.Int   ((int)securityLog.PermType)+"";
			}
			if(securityLog.UserNum != oldSecurityLog.UserNum) {
				if(command!=""){ command+=",";}
				command+="UserNum = "+POut.Long(securityLog.UserNum)+"";
			}
			//LogDateTime not allowed to change
			if(securityLog.LogText != oldSecurityLog.LogText) {
				if(command!=""){ command+=",";}
				command+="LogText = '"+POut.String(securityLog.LogText)+"'";
			}
			if(securityLog.PatNum != oldSecurityLog.PatNum) {
				if(command!=""){ command+=",";}
				command+="PatNum = "+POut.Long(securityLog.PatNum)+"";
			}
			if(securityLog.CompName != oldSecurityLog.CompName) {
				if(command!=""){ command+=",";}
				command+="CompName = '"+POut.String(securityLog.CompName)+"'";
			}
			if(securityLog.FKey != oldSecurityLog.FKey) {
				if(command!=""){ command+=",";}
				command+="FKey = "+POut.Long(securityLog.FKey)+"";
			}
			if(securityLog.LogSource != oldSecurityLog.LogSource) {
				if(command!=""){ command+=",";}
				command+="LogSource = "+POut.Int   ((int)securityLog.LogSource)+"";
			}
			if(command==""){
				return false;
			}
			command="UPDATE securitylog SET "+command
				+" WHERE SecurityLogNum = "+POut.Long(securityLog.SecurityLogNum);
			Db.NonQ(command);
			return true;
		}