public bool PosTest1()
    {
        bool retVal = true;
        SecurityException sec;
        string msg;
        string str;

        TestLibrary.TestFramework.BeginScenario("PosTest1: SecurityException.ToString()");

        try
        {
            msg = TestLibrary.Generator.GetString(-55, false, c_MINLEN, c_MAXLEN);
            sec = new SecurityException(msg);

            str = sec.ToString();

            if (null == str)
            {
                TestLibrary.TestFramework.LogError("000", "ToString returned null");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
예제 #2
0
    public bool PosTest1()
    {
        bool retVal = true;
        SecurityException sec;
        string msg;

        TestLibrary.TestFramework.BeginScenario("PosTest1: SecurityException.Ctor(string)");

        try
        {
            msg = TestLibrary.Generator.GetString(-55, false, c_MINLEN, c_MAXLEN);
            sec = new SecurityException(msg);

            if (!sec.Message.Equals(msg))
            {
                TestLibrary.TestFramework.LogError("000", "Message mismatch: Expected("+msg+") Actual("+sec.Message+")");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
예제 #3
0
    public bool PosTest1()
    {
        bool retVal = true;
        SecurityException sec;

        TestLibrary.TestFramework.BeginScenario("PosTest1: SecurityException.Ctor");

        try
        {
            sec = new SecurityException();

            if (null == sec.Message)
            {
                TestLibrary.TestFramework.LogError("000", "Message is null!");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
예제 #4
0
 public void LogEvent(TraceEventType type, ushort eventLogCategory, uint eventId, bool shouldTrace, params string[] values)
 {
     if (EventLogger.canLogEvent)
     {
         try
         {
             this.SafeLogEvent(type, eventLogCategory, eventId, shouldTrace, values);
         }
         catch (SecurityException securityException1)
         {
             SecurityException securityException = securityException1;
             EventLogger.canLogEvent = false;
             if (shouldTrace && this.diagnosticTrace != null && TraceCore.HandledExceptionIsEnabled(this.diagnosticTrace))
             {
                 TraceCore.HandledException(this.diagnosticTrace, securityException);
             }
         }
     }
 }
예제 #5
0
    public bool PosTest1()
    {
        bool retVal = true;
        SecurityException sec;
        Exception eh;
        string msg1;
        string msg2;

        TestLibrary.TestFramework.BeginScenario("PosTest1: SecurityException.Ctor(string, exception)");

        try
        {
            msg1 = TestLibrary.Generator.GetString(-55, false, c_MINLEN, c_MAXLEN);
            msg2 = TestLibrary.Generator.GetString(-55, false, c_MINLEN, c_MAXLEN);
            eh   = new Exception(msg2);
            sec  = new SecurityException(msg1, eh);

            if (!sec.Message.Equals(msg1))
            {
                TestLibrary.TestFramework.LogError("000", "Message mismatch: Expected("+msg1+") Actual("+sec.Message+")");
                retVal = false;
            }

            if (null == sec.InnerException)
            {
                TestLibrary.TestFramework.LogError("001", "InnerException should not be null");
                retVal = false;
            }

            if (null != sec.InnerException && !sec.InnerException.Message.Equals(msg2))
            {
                TestLibrary.TestFramework.LogError("002", "InnerException Message mismatch: Expected("+msg2+") Actual("+sec.InnerException.Message+")");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
예제 #6
0
 public void LogEvent(TraceEventType type, ushort eventLogCategory, uint eventId, bool shouldTrace, string[] values)
 {
     if (EventLogger.canLogEvent)
     {
         try
         {
             this.SafeLogEvent(type, eventLogCategory, eventId, shouldTrace, values);
         }
         catch (SecurityException securityException1)
         {
             SecurityException securityException = securityException1;
             EventLogger.canLogEvent = false;
             if (shouldTrace)
             {
                 Fx.Exception.TraceHandledException(securityException, TraceEventType.Information);
             }
         }
     }
 }
        public override void Arrange()
        {
            var actionGenerator =
                new DomainGenerator()
                .With <Action <IList <Exception> > >(
                    // repetition increases likelyhood
                    l => l.Add(null),
                    l => l.Add(null),
                    l => l.Add(null),
                    l => l.Add(null),
                    l =>
            {
                Exception exception = new BusinessException();
                l.Add(exception);
                throw exception;
            },
                    l =>
            {
                Exception exception = new SecurityException();
                l.Add(exception);
                throw exception;
            },
                    l =>
            {
                Exception exception = new UnknownException();
                l.Add(exception);
                throw exception;
            },
                    l =>
            {
                Exception exception = new AnotherUnknownException();
                l.Add(exception);
                throw exception;
            });

            input =
                new DomainGenerator()
                .With <ProcessOneWayRequestsInput>(
                    opt => opt.For(i => i.OneWayRequestsAndHandlers, new OneWayRequestsAndHandlers()))
                .With <ProcessOneWayRequestsInput>(
                    opt => opt.For(i => i.Actions, actionGenerator.Many <Action <IList <Exception> > >(3, 3).ToList()))
                .One <ProcessOneWayRequestsInput>();
        }
        public override void Arrange()
        {
            var actionGenerator =
                new DomainGenerator()
                    .With<Action<IList<Exception>>>(
                        // repetition increases likelyhood
                    l => l.Add(null),
                    l => l.Add(null),
                    l => l.Add(null),
                    l => l.Add(null),
                    l =>
                        {
                            Exception exception = new BusinessException();
                            l.Add(exception);
                            throw exception;
                        },
                    l =>
                        {
                            Exception exception = new SecurityException();
                            l.Add(exception);
                            throw exception;
                        },
                    l =>
                        {
                            Exception exception = new UnknownException();
                            l.Add(exception);
                            throw exception;
                        },
                    l =>
                        {
                            Exception exception = new AnotherUnknownException();
                            l.Add(exception);
                            throw exception;
                        });

            input =
                new DomainGenerator()
                    .With<ProcessOneWayRequestsInput>(
                        opt => opt.For(i => i.OneWayRequestsAndHandlers, new OneWayRequestsAndHandlers()))
                    .With<ProcessOneWayRequestsInput>(
                        opt => opt.For(i => i.Actions, actionGenerator.Many<Action<IList<Exception>>>(3, 3).ToList()))
                    .One<ProcessOneWayRequestsInput>();
        }
예제 #9
0
    public bool PosTest1()
    {
        bool retVal = true;
        SecurityException sec;
        Exception         eh;
        string            msg1;
        string            msg2;

        TestLibrary.TestFramework.BeginScenario("PosTest1: SecurityException.Ctor(string, exception)");

        try
        {
            msg1 = TestLibrary.Generator.GetString(-55, false, c_MINLEN, c_MAXLEN);
            msg2 = TestLibrary.Generator.GetString(-55, false, c_MINLEN, c_MAXLEN);
            eh   = new Exception(msg2);
            sec  = new SecurityException(msg1, eh);

            if (!sec.Message.Equals(msg1))
            {
                TestLibrary.TestFramework.LogError("000", "Message mismatch: Expected(" + msg1 + ") Actual(" + sec.Message + ")");
                retVal = false;
            }

            if (null == sec.InnerException)
            {
                TestLibrary.TestFramework.LogError("001", "InnerException should not be null");
                retVal = false;
            }

            if (null != sec.InnerException && !sec.InnerException.Message.Equals(msg2))
            {
                TestLibrary.TestFramework.LogError("002", "InnerException Message mismatch: Expected(" + msg2 + ") Actual(" + sec.InnerException.Message + ")");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
        internal static bool IsCustomTypeDeserializationAllowed(Type type, out SecurityException ex)
        {
            ex = null;

            // allow all primitive and basic types
            if (type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(TimeSpan) || type == typeof(decimal))
            {
                return(true);
            }

            if (AjaxPro.Utility.Settings.IsCustomTypesDeserializationDisabled)
            {
                bool isCustomTypeAllowed = false;

                foreach (var s in AjaxPro.Utility.Settings.JsonDeserializationCustomTypesAllowed)
                {
                    if ((s.EndsWith("*") && type.FullName.StartsWith(s.Substring(0, s.Length - 1), StringComparison.InvariantCultureIgnoreCase)) || s == type.FullName)
                    {
                        isCustomTypeAllowed = true;
                        break;
                    }
                }

                if (!isCustomTypeAllowed)
                {
                    ex = new SecurityException(AjaxPro.Utility.Settings.DebugEnabled ? "The type '" + type.Name + "' is not allowed to be deserialized." : "At least one type passed is not allowed to be deserialized.");
                    return(false);
                }
            }
            else
            {
                foreach (var s in AjaxPro.Utility.Settings.JsonDeserializationCustomTypesDenied)
                {
                    if ((s.EndsWith("*") && type.FullName.StartsWith(s.Substring(0, s.Length - 1), StringComparison.InvariantCultureIgnoreCase)) || s == type.FullName)
                    {
                        ex = new SecurityException(AjaxPro.Utility.Settings.DebugEnabled ? "The type '" + type.Name + "' is not allowed to be deserialized." : "At least one type passed is not allowed to be deserialized.");
                        return(false);
                    }
                }
            }

            return(true);
        }
예제 #11
0
        /// <summary>
        /// this handler written beaded on the SSON ApiExceptionHandler and how we are throw the exception
        /// in Tahaluf.FIHS.SingleSignOn.API.Handlers.ApiExceptionHandler
        /// </summary>
        /// <param name="webException"></param>
        /// <returns></returns>
        private static Exception HandleApiWebException(WebException webException)
        {
            Exception exception = webException;

            if (webException?.Response is System.Net.HttpWebResponse webResponse)
            {
                if (webResponse?.StatusCode == HttpStatusCode.Unauthorized)
                {
                    exception = new SecurityException();
                }

                if (webResponse?.StatusCode == HttpStatusCode.Forbidden)
                {
                    exception = new UnauthorizedAccessException();
                }
            }

            return(exception);
        }
        public ActionResult LoginPost(string provider)
        {
            IdentityProviderClientConfigurationElement providerConfig = OpenIdConnectUtilities.GetIdentityProviderFromConfiguration(provider);

            switch (providerConfig.ProviderType)
            {
            case IdentityProviderType.OpenIdConnect:
                this.ControllerContext.HttpContext.GetOwinContext().Authentication.Challenge(providerConfig.Name);
                return(new HttpUnauthorizedResult());

            case IdentityProviderType.ACS:

                // Storing cookie with current provider (used in Logoff).
                OpenIdConnectUtilities.SetCookie(
                    this.HttpContext,
                    OpenIdConnectUtilities.CookieCurrentProvider,
                    providerConfig.Name);
                OpenIdConnectUtilities.SetCookie(
                    this.HttpContext,
                    OpenIdConnectUtilities.CookieCurrentProviderType,
                    providerConfig.ProviderType.ToString());

                string url = string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}v2/wsfederation?wa=wsignin1.0&wtrealm={1}",
                    providerConfig.Issuer,
                    providerConfig.RedirectUrl);
                this.Response.Redirect(url, true);
                break;

            default:
                SecurityException securityException =
                    new SecurityException(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "The identity provider type {0} is not supported",
                            providerConfig.ProviderType));
                throw securityException;
            }

            return(null);
        }
        public void TestSecurityExceptionReturnsNotFoundResult()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <ExceptionHandlerFilterAttribute> >();
            var logger     = loggerMock.Object;

            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(
                lf => lf.CreateLogger(It.IsAny <String>()))
            .Returns(logger);

            var exception = new SecurityException("A security message");

            var httpContextMock  = new Mock <HttpContext>();
            var routeData        = new RouteData();
            var actionDescriptor = new ActionDescriptor();
            var actionContext    = new ActionContext(httpContextMock.Object, routeData, actionDescriptor);

            var exceptionContext = new ExceptionContext(actionContext, new List <IFilterMetadata>());

            exceptionContext.Exception        = exception;
            exceptionContext.ExceptionHandled = false;

            // Act
            var filter = new ExceptionHandlerFilterAttribute(loggerFactoryMock.Object);

            filter.OnException(exceptionContext);

            // Assert
            Assert.NotNull(exceptionContext.Result);
            Assert.IsType <ForbiddenObjectResult>(exceptionContext.Result);

            String expectedMessage = "Access to this resource is forbidden";
            var    resultObject    = (ForbiddenObjectResult)(exceptionContext.Result);

            Assert.IsType <ApiMessageModel>(resultObject.Value);
            Assert.Equal(expectedMessage, ((ApiMessageModel)resultObject.Value).Message);

            // Commented out because LogWarning is an extension method.  Need to figure out how to test
            //loggerMock.Verify(l => l.LogWarning(It.IsAny<EventId>(), exception, notFoundMessage), Times.Once);
        }
        public IPrincipal Authenticate(string deviceId, string deviceSecret, string clientId, string clientSecret)
        {
            // Authenticate
            IPrincipal retVal = null;

            using (IRestClient restClient = new RestClient(this.m_configuration.GetIdpDescription()))
            {
                try
                {
                    // Create grant information
                    OAuthTokenRequest request = new OAuthTokenRequest(clientId, clientSecret);
                    request.Scope = "*";

                    restClient.Requesting += (o, p) =>
                    {
                        p.AdditionalHeaders.Add("X-Device-Authorization", $"BASIC {Convert.ToBase64String(Encoding.UTF8.GetBytes(String.Format("{0}:{1}", deviceId, deviceSecret)))}");
                    };

                    OAuthTokenResponse response = restClient.Post <OAuthTokenRequest, OAuthTokenResponse>("oauth2_token", "application/x-www-form-urlencoded", request);
                    retVal = new TokenClaimsPrincipal(response.AccessToken, response.IdToken ?? response.AccessToken, response.TokenType, response.RefreshToken);
                }
                catch (RestClientException <OAuthTokenResponse> ex)
                {
                    Trace.TraceError("REST client exception: {0}", ex.Message);
                    var se = new SecurityException($"Error executing OAuth request: {ex.Result.Error}", ex);
                    se.Data.Add("detail", ex.Result);
                    throw se;
                }
                catch (SecurityException ex)
                {
                    Trace.TraceError("TOKEN exception: {0}", ex.Message);
                    throw new SecurityException($"Security error: {ex.Message}", ex);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Generic exception: {0}", ex);
                    throw;
                }

                return(retVal);
            }
        }
        /// <summary>
        /// Xoa mot ung dung
        /// </summary>
        /// <param name="application">Doi tuong ung dung muon xoa</param>
        public void Remove(Application application)
        {
            try
            {
                // Create SQL parameters
                SqlParameter prmApplicationID = new SqlParameter("@ApplicationID", SqlDbType.Int, 4);
                prmApplicationID.Direction = ParameterDirection.Input;
                prmApplicationID.Value     = application.ApplicationID;

                SqlParameter prmErrorNumber = new SqlParameter("@ErrorNumber", SqlDbType.Int, 4);
                prmErrorNumber.Direction = ParameterDirection.Output;

                SqlParameter prmErrorMessage = new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, 100);
                prmErrorMessage.Direction = ParameterDirection.Output;


                // execute stored procedure to delete application
                Database.ExecuteNonQuery(
                    "UspRemoveApplication",
                    CommandType.StoredProcedure
                    , prmApplicationID
                    , prmErrorNumber
                    , prmErrorMessage);


                // checking for output errors
                int errorNumber = int.Parse(prmErrorNumber.Value.ToString());

                if (errorNumber > 0)
                {
                    string errorMessage = prmErrorMessage.Value.ToString();

                    SecurityException customEx = new SecurityException(errorMessage);

                    throw customEx;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="user"></param>
        /// <param name="role"></param>
        public void RemoveUserFromRole(string username, int roleID)
        {
            try
            {
                // create sql parameters
                SqlParameter prmUsername = new SqlParameter("@Username", SqlDbType.VarChar, 128);
                prmUsername.Direction = ParameterDirection.Input;
                prmUsername.Value     = username;

                SqlParameter prmRoleID = new SqlParameter("@RoleID", SqlDbType.Int, 4);
                prmRoleID.Direction = ParameterDirection.Input;
                prmRoleID.Value     = roleID;

                SqlParameter prmErrorNumber = new SqlParameter("@ErrorNumber", SqlDbType.Int, 4);
                prmErrorNumber.Direction = ParameterDirection.Output;

                SqlParameter prmErrorMessage = new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, 150);
                prmErrorMessage.Direction = ParameterDirection.Output;

                // execute procedure
                Database.ExecuteNonQuery("UspRemoveUserFromRole", CommandType.StoredProcedure
                                         , prmUsername
                                         , prmRoleID
                                         , prmErrorNumber
                                         , prmErrorMessage);

                int errorNumber = int.Parse(prmErrorNumber.Value.ToString());

                if (errorNumber > 0)
                {
                    string errorMessage = prmErrorMessage.Value.ToString();

                    SecurityException customEx = new SecurityException(errorMessage);

                    throw customEx;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #17
0
        private async Task <MinIdpUserData> guardedIdpAccess(Func <Guid, Task <MinIdpUserData> > body)
        {
            var rel = Guid.NewGuid();

            try
            {
                if (ComponentEffectiveLogLevel < MessageType.Trace)
                {
                    WriteLog(MessageType.DebugA, nameof(guardedIdpAccess), "#001 IDP.Call", related: rel);
                }

                var result = await body(rel);

                if (ComponentEffectiveLogLevel < MessageType.Trace)
                {
                    WriteLog(MessageType.DebugA, nameof(guardedIdpAccess), "#002 IDP.Call result. User name: `{0}`".Args(result?.Name), related: rel);
                }

                return(result);
            }
            catch (Exception cause)
            {
                if (ComponentEffectiveLogLevel < MessageType.Trace)
                {
                    WriteLog(MessageType.DebugError, nameof(guardedIdpAccess), "#003 IDP.Call result exception: {0}".Args(cause.ToMessageWithType()), related: rel);
                }

                if (cause is WebCallException wce && wce.HttpStatusCode == 404)
                {
                    if (ComponentEffectiveLogLevel < MessageType.Trace)
                    {
                        WriteLog(MessageType.DebugA, nameof(guardedIdpAccess), "#004 Got WCE-404", related: rel);
                    }

                    return(null);//404 is treated as "user not found"
                }

                var error = new SecurityException(StringConsts.SECURITY_IDP_UPSTREAM_CALL_ERROR.Args(cause.ToMessageWithType()), cause);
                WriteLog(MessageType.CriticalAlert, nameof(guardedIdpAccess), error.Message, error: error, related: rel);
                throw error;
            }
        }
예제 #18
0
        /// <summary>
        /// Update resource status
        /// </summary>
        /// <param name="resourceID">Resource ID</param>
        /// <param name="status">New Status</param>
        public void UpdateResourceStatus(int resourceID, bool status)
        {
            try
            {
                // create sql parameters
                SqlParameter prmResourceID = new SqlParameter("@ResourceID", SqlDbType.Int, 4);
                prmResourceID.Direction = ParameterDirection.Input;

                SqlParameter prmStatus = new SqlParameter("@Status", SqlDbType.Bit, 1);
                prmStatus.Direction = ParameterDirection.Input;

                SqlParameter prmErrorNumber = new SqlParameter("@ErrorNumber", SqlDbType.Int, 4);
                prmErrorNumber.Direction = ParameterDirection.Output;

                SqlParameter prmErrorMessage = new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, 100);
                prmErrorMessage.Direction = ParameterDirection.Output;

                // asign param value
                prmResourceID.Value = resourceID;
                prmStatus.Value     = status;

                // execute query
                Database.ExecuteNonQuery("UspUpdateResourceStatus", CommandType.StoredProcedure
                                         , prmResourceID
                                         , prmStatus
                                         , prmErrorNumber
                                         , prmErrorMessage);

                int errorNumber = int.Parse(prmErrorNumber.Value.ToString());

                if (errorNumber > 0)
                {
                    string            errorMessage = prmErrorMessage.Value.ToString();
                    SecurityException customEx     = new SecurityException(errorMessage);
                    throw customEx;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb currentWeb = SPContext.Current.Web;

            if (currentWeb.Name.ToLower().Equals("policies") || currentWeb.ServerRelativeUrl.ToLower().Equals("/policies"))
            {
                return;
            }

            Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            SPUser currentUser = currentWeb.CurrentUser;

            var currentPage = Request.CurrentExecutionFilePath;

            PermissionGroupDAL = new PermissionGroupDAL(SPContext.Current.Site.RootWeb.Url);
            var groups = new List <string>();

            var items = currentWeb.CurrentUser.Groups.GetEnumerator();

            while (items.MoveNext())
            {
                groups.Add(items.Current.ToString());
            }

            var hasPermission = PermissionGroupDAL.IsAuthorizedOnPage(SPContext.Current.Site.RootWeb, currentPage, groups);

            if (!hasPermission)
            {
                var ex = new SecurityException();
                SPUtility.HandleAccessDenied(ex);
            }

            if (currentUser.IsSiteAdmin == false && UserPermission.IsCurrentUserInGroup(StringConstant.Group.CommonAccountGroupName) && HttpContext.Current.Session[StringConstant.EmployeeLogedin] == null)
            {
                string url = HttpContext.Current.Request.Url.AbsoluteUri;
                if (url.Contains(StringConstant.PageLoginURL) || url.Contains(StringConstant.PageHomeURL))
                {
                    return;
                }
                Response.Redirect(StringConstant.PageLoginURL);
            }
        }
예제 #20
0
        public TWindow LoadWindow <TWindowViewModel, TWindow>(TWindowViewModel windowViewModel)
            where TWindowViewModel : class, IWindowViewModel, IClaim
            where TWindow : class, IWindow
        {
            bool isAllowed = SecurityChecker.AmIAllowed <TWindowViewModel>();

            if (isAllowed)
            {
                Window.Value             = (IWindow)Container.Resolve <TWindow>();
                Window.Value.DataContext = this;
                Window.Value.Show();
                LoadedCommand.Execute(null);

                return((TWindow)Window.Value);
            }
            else
            {
                throw SecurityException.CreateCoreException <TWindowViewModel>(windowViewModel);
            }
        }
예제 #21
0
        private static Exception convertException(WebException exp)
        {
            Exception exp2 = exp;
            var       s    = readString(exp.Response.GetResponseStream());

            exp2 = new Exception(s, exp);
            if (exp.Response is HttpWebResponse)
            {
                if (string.IsNullOrWhiteSpace(s))
                {
                    s = "Unauthorized access.";
                }
                var httpExp = exp.Response as HttpWebResponse;
                if (httpExp.StatusCode == HttpStatusCode.Unauthorized)
                {
                    exp2 = new SecurityException(s, exp);
                }
            }
            return(exp2);
        }
예제 #22
0
 private bool RequiresMemberAccessForCreate(SecurityException securityException)
 {
     if (!DataContract.IsTypeVisible(base.UnderlyingType))
     {
         if (securityException != null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityException(System.Runtime.Serialization.SR.GetString("PartialTrustIXmlSerializableTypeNotPublic", new object[] { DataContract.GetClrTypeFullName(base.UnderlyingType) }), securityException));
         }
         return(true);
     }
     if (!DataContract.ConstructorRequiresMemberAccess(this.GetConstructor()))
     {
         return(false);
     }
     if (securityException != null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityException(System.Runtime.Serialization.SR.GetString("PartialTrustIXmlSerialzableNoPublicConstructor", new object[] { DataContract.GetClrTypeFullName(base.UnderlyingType) }), securityException));
     }
     return(true);
 }
예제 #23
0
        public double RegionConsumtion(string region)  //srednja potronja za odredjeni region
        {
            if (StateService.stateService != EStateServers.Primarni)
            {
                MyException ex = new MyException("Error! Not primary\n");
                throw new FaultException <MyException>(ex);
            }

            CustomPrincipal principal = Thread.CurrentPrincipal as CustomPrincipal;

            if (!principal.IsInRole(Permissions.ReadingRegionAvgConsumption.ToString()))
            {
                SecurityException ex = new SecurityException("Error! IS NOT A READER\n");
                throw new FaultException <SecurityException>(ex);
            }

            if (!File.Exists(DataBase.FileName))
            {
                MyException ex = new MyException("Error! file not find\n");
                throw new FaultException <MyException>(ex);
            }

            double suma  = 0;
            int    count = 0;

            lock (DataBase.lockObject)
            {
                foreach (var item in DataBase.consumers.Values)
                {
                    if (item.Region == region)
                    {
                        suma += item.Consumation;
                        count++;
                    }
                }
            }

            Console.WriteLine("Srednja vrednost za grad " + region + " je {0}", Math.Round((suma / count), 2));

            return(suma / count);
        }
예제 #24
0
        private void OpenWriteAsyncResponseCallback(IAsyncResult result)
        {
            Exception ex = null;

            try {
                WebResponse response = request.EndGetResponse(result);
                ProcessResponse(response);
            }
            catch (SecurityException se) {
                // SecurityException inside a SecurityException (not a WebException) for SL compatibility
                ex = new SecurityException(String.Empty, se);
            }
            catch (Exception e) {
                ex = new WebException("Could not complete operation.", e, WebExceptionStatus.UnknownError, null);
            }
            finally {
                callback_data.sync_context.Post(delegate(object sender) {
                    OnWriteStreamClosed(new WriteStreamClosedEventArgs(ex));
                }, null);
            }
        }
예제 #25
0
        public void SetPassword(string username, string password)
        {
            try
            {
                // create sql parameters
                SqlParameter prmUsername = new SqlParameter("@Username", SqlDbType.VarChar, 128);
                prmUsername.Direction = ParameterDirection.Input;
                prmUsername.Value     = username;

                SqlParameter prmPassword = new SqlParameter("@Password", SqlDbType.VarChar, 64);
                prmPassword.Direction = ParameterDirection.Input;
                prmPassword.Value     = password;

                SqlParameter prmErrorNumber = new SqlParameter("@ErrorNumber", SqlDbType.Int, 4);
                prmErrorNumber.Direction = ParameterDirection.Output;

                SqlParameter prmErrorMessage = new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, 150);
                prmErrorMessage.Direction = ParameterDirection.Output;

                // Execute procedure
                Database.ExecuteNonQuery("UspSetUserPassword", CommandType.StoredProcedure
                                         , prmUsername
                                         , prmPassword
                                         , prmErrorNumber
                                         , prmErrorMessage);

                int errorNumber = int.Parse(prmErrorNumber.Value.ToString());

                if (errorNumber > 0)
                {
                    string            errorMessage = prmErrorMessage.Value.ToString();
                    SecurityException customEx     = new SecurityException(errorMessage);
                    throw customEx;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="operation"></param>
        public void Remove(Operation operation)
        {
            try
            {
                // create sql param
                SqlParameter prmOperationCode = new SqlParameter("@OperationCode", SqlDbType.Int, 4);
                prmOperationCode.Direction = ParameterDirection.Input;
                prmOperationCode.Value     = operation.OperationCode;

                SqlParameter prmResourceTypeCode = new SqlParameter("@ResourceTypeCode", SqlDbType.VarChar, 50);
                prmResourceTypeCode.Direction = ParameterDirection.Input;
                prmResourceTypeCode.Value     = operation.ResourceTypeCode;

                SqlParameter prmErrorNumber = new SqlParameter("@ErrorNumber", SqlDbType.Int, 4);
                prmErrorNumber.Direction = ParameterDirection.Output;

                SqlParameter prmErrorMessage = new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, 100);
                prmErrorMessage.Direction = ParameterDirection.Output;

                // execute stored
                Database.ExecuteNonQuery("UspRemoveOperation", CommandType.StoredProcedure
                                         , prmOperationCode
                                         , prmResourceTypeCode
                                         , prmErrorNumber
                                         , prmErrorMessage);

                int errorNumber = int.Parse(prmErrorNumber.Value.ToString());

                if (errorNumber > 0)
                {
                    string            errorMessage = prmErrorMessage.Value.ToString();
                    SecurityException customEx     = new SecurityException(errorMessage);
                    throw customEx;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="resourceType"></param>
        public void Update(ResourceType resourceType)
        {
            try
            {
                // create sql parameters
                SqlParameter prmResourceTypeCode = new SqlParameter("@ResourceTypeCode", SqlDbType.VarChar, 50);
                prmResourceTypeCode.Direction = ParameterDirection.Input;
                prmResourceTypeCode.Value     = resourceType.ResourceTypeCode;

                SqlParameter prmName = new SqlParameter("@Name", SqlDbType.NVarChar, 50);
                prmName.Direction = ParameterDirection.Input;
                prmName.Value     = resourceType.Name;

                SqlParameter prmErrorNumber = new SqlParameter("@ErrorNumber", SqlDbType.Int, 4);
                prmErrorNumber.Direction = ParameterDirection.Output;

                SqlParameter prmErrorMessage = new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, 150);
                prmErrorMessage.Direction = ParameterDirection.Output;

                // Execute procedure
                Database.ExecuteNonQuery("UspUpdateResourceType", CommandType.StoredProcedure
                                         , prmResourceTypeCode
                                         , prmName
                                         , prmErrorNumber
                                         , prmErrorMessage);

                int errorNumber = int.Parse(prmErrorNumber.Value.ToString());

                if (errorNumber > 0)
                {
                    string            errorMessage = prmErrorMessage.Value.ToString();
                    SecurityException customEx     = new SecurityException(errorMessage);
                    throw customEx;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #28
0
        public bool AddConsumer(Consumer consumer)
        {
            if (StateService.stateService != EStateServers.Primarni)
            {
                MyException ex = new MyException("Error! Not primary\n");
                throw new FaultException <MyException>(ex);
            }

            CustomPrincipal principal = Thread.CurrentPrincipal as CustomPrincipal;

            if (!principal.IsInRole(Permissions.Writting.ToString()))
            {
                SecurityException ex = new SecurityException("Error! IS NOT A Writer\n");
                throw new FaultException <SecurityException>(ex);
            }
            // CustomAuditBehavior.AuthenticationSuccess(principal.Identity.Name.ToString());
            if (!File.Exists(DataBase.FileName))
            {
                MyException ex = new MyException("Error! file not found\n");
                throw new FaultException <MyException>(ex);
            }

            if (DataBase.consumers.ContainsKey(consumer.ConsumerID))
            {
                return(false);
            }

            lock (DataBase.lockObject)
            {
                DataBase.consumers[consumer.ConsumerID]      = consumer;
                DataBase.consumersDelta[consumer.ConsumerID] = consumer;
                using (StreamWriter file = File.AppendText(DataBase.FileName))
                {
                    file.WriteLine(CreateConsumerString(consumer.ConsumerID, consumer.Region, consumer.City, consumer.Year, consumer.Consumation));
                }
            }

            return(true);
        }
예제 #29
0
        internal static bool ShouldWrap(Exception exception, out Status status)
        {
            if (exception is RpcException)
            {
                status = default;
                return(false);
            }
            status = new Status(exception switch
            {
#pragma warning disable IDE0059 // needs more recent compiler than the CI server has
                OperationCanceledException a => StatusCode.Cancelled,
                ArgumentException b => StatusCode.InvalidArgument,
                NotImplementedException c => StatusCode.Unimplemented,
                NotSupportedException d => StatusCode.Unimplemented,
                SecurityException e => StatusCode.PermissionDenied,
                EndOfStreamException f => StatusCode.OutOfRange,
                FileNotFoundException g => StatusCode.NotFound,
                DirectoryNotFoundException h => StatusCode.NotFound,
                TimeoutException i => StatusCode.DeadlineExceeded,
#pragma warning restore IDE0059 // needs more recent compiler than the CI server has
                _ => StatusCode.Unknown,
            }, exception.Message, exception);
        private void UploadStringResponseAsyncCallback(IAsyncResult result)
        {
            string    data   = null;
            Exception ex     = null;
            bool      cancel = false;

            try
            {
                WebResponse response = request.EndGetResponse(result);
                Stream      stream   = ProcessResponse(response);

                using (StreamReader sr = new StreamReader(stream, encoding, true))
                {
                    data = sr.ReadToEnd();
                }
            }
            catch (WebException web)
            {
                cancel = (web.Status == WebExceptionStatus.RequestCanceled);
                ex     = web;
            }
            catch (SecurityException se)
            {
                // SecurityException inside a SecurityException (not a WebException) for SL compatibility
                ex = new SecurityException(String.Empty, se);
            }
            catch (Exception e)
            {
                ex = new WebException("Could not complete operation.", e, WebExceptionStatus.UnknownError, null);
            }
            finally
            {
                callback_data.sync_context.Post(delegate(object sender)
                {
                    OnUploadStringCompleted(new UploadStringCompletedEventArgs(data, ex, cancel, callback_data.user_token));
                }, null);
            }
        }
예제 #31
0
 public void RemovePerson(long jmbg, string username)
 {
     if (SystemUserService.IsUserAuthenticated(username))
     {
         if (SystemUserService.IsUserAuthorized(username, ERights.Delete))
         {
             if (Database.persons.ContainsKey(jmbg))
             {
                 Console.WriteLine("{1} : Deleted person with JMBG : {0}", jmbg, DateTime.Now);
                 Database.persons.Remove(jmbg);
             }
             else
             {
                 DataException ex = new DataException()
                 {
                     Message = "Idem with ID this cannot be found."
                 };
                 throw new FaultException <DataException>(ex);
             }
         }
         else
         {
             SecurityException ex = new SecurityException()
             {
                 Reason = "User not athorized to execute this operation."
             };
             throw new FaultException <SecurityException>(ex);
         }
     }
     else
     {
         SecurityException ex = new SecurityException()
         {
             Reason = "User is not authenticated."
         };
         throw new FaultException <SecurityException>(ex);
     }
 }
예제 #32
0
        /// <summary>
        /// Authorizes the user
        /// </summary>
        /// <param name="e"></param>
        /// <remarks>
        /// Checks if the page exists outside of the /umbraco route, in which case the request will not have been authenticated for the back office
        /// so we'll force authentication.
        /// </remarks>
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            //If this is not a back office request, then the module won't have authenticated it, in this case we
            // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior
            // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge
            if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, Current.Configs.Global()) == false)
            {
                var http   = new HttpContextWrapper(Context);
                var ticket = http.GetUmbracoAuthTicket();
                http.AuthenticateCurrentRequest(ticket, true);
            }

            try
            {
                Security.ValidateCurrentUser(true);
                _hasValidated = true;

                if (!Security.ValidateUserApp(CurrentApp))
                {
                    var ex = new SecurityException(String.Format("The current user doesn't have access to the section/app '{0}'", CurrentApp));
                    Current.Logger.Error <UmbracoEnsuredPage>(ex, "Tried to access '{CurrentApp}'", CurrentApp);
                    throw ex;
                }
            }
            catch
            {
                // Clear content as .NET transfers rendered content.
                Response.Clear();

                // Ensure the person is definitely logged out
                UmbracoContext.Current.Security.ClearCurrentLogin();

                // Redirect to the login page
                Response.Redirect(SystemDirectories.Umbraco + "#/login", true);
            }
        }
예제 #33
0
        private static string GetPermissionErrorMessage(SecurityException exception)
        {
            switch (exception.PermissionType.Name)
            {
            case nameof(FileIOPermission):
                return("Subroute.io execution environment prevents file system access. Please use other available storage functionality.");

            case nameof(EnvironmentPermission):
                return("Subroute.io execution environment prevents access to system and user environment variables.");

            case nameof(StorePermission):
                return("Subroute.io execution environment prevents access to key and certificate stores.");

            case nameof(RegistryPermission):
                return("Subroute.io execution environment prevents access to the system registry.");

            case nameof(SocketPermission):
                return("Subroute.io execution environment does not allow establishing a connection to or opening a socket.");

            case nameof(UIPermission):
                return("Subroute.io execution environment does not allow creating or accessing user interface components.");

            case nameof(FileDialogPermission):
                return("Subroute.io execution environment does not allow opening or interacting with a file dialog.");

            case nameof(ConfigurationPermission):
                return("Subroute.io execution environment does not allow access to configuration settings.");

            case nameof(EventLogPermission):
                return("Subroute.io execution environment does not allow access to the system event log.");

            case nameof(NetworkInformationPermission):
                return("Subroute.io execution environment does not allow access to information regarding internal network infrastructure.");

            default:
                return("Subroute.io execution environment does not allow file, registry, and certain reflection statements from executing.");
            }
        }
예제 #34
0
        public TControlViewModel LoadContent <TControlViewModel, TControl>(params Arg[] args)
            where TControlViewModel : IControlViewModel, IClaim
            where TControl : IControl
        {
            bool isAllowed = SecurityChecker.AmIAllowed <TControlViewModel>();

            TControlViewModel controlViewModel = GetContent <TControlViewModel, TControl>(true, args);

            if (isAllowed)
            {
                CurrentControlViewModel.Value = controlViewModel;

                CurrentControlViewModel.Value.WindowViewModel.Value = this;

                //controlViewModel.ControlLoadedCommand.Execute(controlViewModel);

                return((TControlViewModel)CurrentControlViewModel.Value);
            }
            else
            {
                throw SecurityException.CreateCoreException <TControlViewModel>(controlViewModel);
            }
        }
        private bool IsValidSharedSecret()
        {
            SecurityException error = null;
            var isValid             = true;

            if (string.IsNullOrWhiteSpace(SharedSecret))
            {
                error = new SecurityException("The SPE shared secret is not set. Add a child <SharedSecret> element in the SPE <authenticationProvider> config (Spe.config) and set a secure shared secret, e.g. a 64-char random string.");
            }

            if (double.TryParse(SharedSecret, out _))
            {
                error = new SecurityException("The SPE shared secret is not set, or was set to a numeric value. Add a child <SharedSecret> element in the SPE <authenticationProvider> config (Spe.config) and set a secure shared secret, e.g. a 64-char random string.");
            }

            if (SharedSecret.Length < 30)
            {
                error = new SecurityException("Your SPE shared secret is not long enough. Please make it more than 30 characters for maximum security. You can set this in Spe.config on the <authenticationProvider>.");
            }

            if (error != null)
            {
                isValid = false;
            }

            if (DetailedAuthenticationErrors && error != null)
            {
                throw error;
            }

            if (isValid)
            {
                return(true);
            }

            return(false);
        }
예제 #36
0
		private bool HasRedirectPermission(Uri uri, ref Exception resultException)
		{
			try {
				CheckConnectPermission(uri, Async);
			}
			catch (SecurityException e) {
				resultException = new SecurityException(SR.GetString(SR.net_redirect_perm),
					new WebException(SR.GetString(SR.net_resubmitcanceled), e,
						WebExceptionStatus.ProtocolError, _HttpResponse));

				GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::CheckRedirectPermission", "false");
				return false;
			}

			return true;
		}
예제 #37
0
		void LogSecurityException(SecurityException securityException) {
			Log.Error(TAG, "Invalid location permission. " +
				"You need to use ACCESS_FINE_LOCATION with geofences", securityException);
		}