According the Owasp Code Review Guide Why Is Error Handling Important

Mistake Handling Crook Canvass¶

Introduction¶

Error treatment is a part of the overall security of an application. Except in movies, an attack ever begins with a Reconnaissance phase in which the attacker will attempt to get together as much technical information (ofttimes name and version properties) every bit possible about the target, such as the application server, frameworks, libraries, etc.

Unhandled errors can assist an attacker in this initial phase, which is very important for the rest of the assail.

The following link provides a description of the different phases of an attack.

Context¶

Issues at the error treatment level can reveal a lot of information near the target and can also exist used to place injection points in the target'southward features.

Beneath is an example of the disclosure of a engineering science stack, here the Struts2 and Tomcat versions, via an exception rendered to the user:

                                    HTTP Condition 500 - For input string: "null"  type Exception study  bulletin For input string: "aught"  description The server encountered an internal fault that prevented it from fulfilling this request.  exception  java.lang.NumberFormatException: For input string: "null"     java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)     java.lang.Integer.parseInt(Integer.java:492)     coffee.lang.Integer.parseInt(Integer.coffee:527)     sun.reverberate.NativeMethodAccessorImpl.invoke0(Native Method)     dominicus.reverberate.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.coffee:57)     dominicus.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.coffee:43)     java.lang.reflect.Method.invoke(Method.java:606)     com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)     com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.coffee:289)     com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)     org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)     com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.coffee:246)     ...  note: The total stack trace of the root crusade is bachelor in the Apache Tomcat/7.0.56 logs.                                  

Below is an example of disclosure of a SQL query mistake, along with the site installation path, that can be used to identify an injection point:

                                    Warning: odbc_fetch_array() expects parameter /1 to be resources, boolean given in D:\app\index_new.php on line 188                                  

The OWASP Testing Guide provides dissimilar techniques to obtain technical data from an awarding.

Objective¶

The article shows how to configure a global error handler as part of your application's runtime configuration. In some cases, it may exist more efficient to define this fault handler as part of your code. The outcome being that when an unexpected error occurs then a generic response is returned past the awarding merely the fault details are logged server side for investigation, and not returned to the user.

The following schema shows the target arroyo:

Overview

Equally most recent awarding topologies are API based, we presume in this article that the backend exposes only a REST API and does non contain any user interface content. The awarding should try and exhaustively cover all possible failure modes and employ 5xx errors only to bespeak responses to requests that it cannot fulfill, just not provide whatsoever content as office of the response that would reveal implementation details.

For the fault logging performance itself, the logging cheat canvass should exist used. This commodity focuses on the error treatment part.

Proffer¶

For each engineering stack, the following configuration options are proposed:

Standard Coffee Web Application¶

For this kind of awarding, a global error handler can be configured at the spider web.xml deployment descriptor level.

We propose hither a configuration that tin be used from Servlet specification version ii.5 and higher up.

With this configuration, any unexpected error will cause a redirection to the page error.jsp in which the error will be traced and a generic response will be returned.

Configuration of the redirection into the web.xml file:

                                                        <?xml version="1.0" encoding="UTF-8"?>                    <web-app                    xmlns:xsi=                    "http://www.w3.org/2001/XMLSchema-instance"                    ns=                    "http://java.dominicus.com/xml/ns/javaee"                    xsi:schemaLocation=                    "http://coffee.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"                    version=                    "3.0"                    >                    ...                    <error-page>                    <exception-type>coffee.lang.Exception</exception-type>                    <location>/error.jsp</location>                    </fault-page>                    ...                    </web-app>                                  

Content of the error.jsp file:

                                                        <%                    @                    folio                    language                    =                    "coffee"                    isErrorPage                    =                    "truthful"                    contentType                    =                    "awarding/json; charset=UTF-8"                    pageEncoding                    =                    "UTF-viii"                    %>                    <%                    String                    errorMessage                    =                    exception                    .                    getMessage                    ();                    //Log the exception via the content of the implicit variable named "exception"                    //...                    //Nosotros build a generic response with a JSON format because we are in a Remainder API app context                    //We too add an HTTP response header to signal to the client app that the response is an error                    response                    .                    setHeader                    (                    "X-Fault"                    ,                    "true"                    );                    //Note that we're using an internal server error response                    //In some cases it may be prudent to render 4xx error codes, when we take misbehaving clients                    response                    .                    setStatus                    (                    500                    );                    %>                    {                    "message"                    :                    "An error occur, please retry"                    }                                  

Coffee SpringMVC/SpringBoot spider web application¶

With SpringMVC or SpringBoot, y'all can ascertain a global error handler by implementing the following class in your projection.

We indicate to the handler, via the note @ExceptionHandler, to human activity when whatsoever exception extending the class java.lang.Exception is thrown by the application.

                                                        import                    net.minidev.json.JSONObject                    ;                    import                    org.springframework.http.HttpHeaders                    ;                    import                    org.springframework.http.HttpStatus                    ;                    import                    org.springframework.http.MediaType                    ;                    import                    org.springframework.http.ResponseEntity                    ;                    import                    org.springframework.spider web.bind.annotation.ControllerAdvice                    ;                    import                    org.springframework.web.bind.annotation.ExceptionHandler                    ;                    import                    org.springframework.web.context.request.WebRequest                    ;                    /**                                          * Global error handler in charge of returning a generic response in instance of unexpected error situation.                                          */                    @ControllerAdvice                    public                    class                    RestResponseEntityExceptionHandler                    {                    @ExceptionHandler                    (                    value                    =                    {                    Exception                    .                    form                    })                    public                    ResponseEntity                    <                    Object                    >                    handleGlobalError                    (                    RuntimeException                    exception                    ,                    WebRequest                    request                    )                    {                    //Log the exception via the content of the parameter named "exception"                    //...                    //Nosotros build a generic response with a JSON format because we are in a Residuum API app context                    //We as well add an HTTP response header to bespeak to the client app that the response is an error                    HttpHeaders                    responseHeaders                    =                    new                    HttpHeaders                    ();                    responseHeaders                    .                    setContentType                    (                    MediaType                    .                    APPLICATION_JSON                    );                    responseHeaders                    .                    set                    (                    "X-ERROR"                    ,                    "true"                    );                    JSONObject                    responseBody                    =                    new                    JSONObject                    ();                    responseBody                    .                    put                    (                    "bulletin"                    ,                    "An mistake occur, delight retry"                    );                    //Note that nosotros're using an internal server fault response                    //In some cases it may be prudent to return 4xx error codes, if we have misbehaving clients                    ResponseEntity                    <                    JSONObject                    >                    response                    =                    new                    ResponseEntity                    <>                    (                    responseBody                    ,                    responseHeaders                    ,                    HttpStatus                    .                    INTERNAL_SERVER_ERROR                    );                    return                    (                    ResponseEntity                    )                    response                    ;                    }                    }                                  

References:

  • Exception treatment with Spring
  • Exception handling with SpringBoot

ASP Internet Cadre spider web application¶

With ASP.Internet Core, you tin can define a global mistake handler past indicating that the exception handler is a dedicated API Controller.

Content of the API Controller dedicated to the error handling:

                                                        using                                                            Microsoft.AspNetCore.Authorisation                    ;                                        using                                                            Microsoft.AspNetCore.Diagnostics                    ;                                        using                                                            Microsoft.AspNetCore.Mvc                    ;                                        using                                                            Organisation                    ;                                        using                                                            System.Collections.Generic                    ;                                        using                                                            System.Net                    ;                                        namespace                                                            MyProject.Controllers                                        {                                                                                /// <summary>                                                            /// API Controller used to intercept and handle all unexpected exception                                                            /// </summary>                                                            [Route("api/[controller]                    ")]                                                            [ApiController]                                                                                [AllowAnonymous]                                                                                public                                                            class                                                            ErrorController                                                            :                                                            ControllerBase                                                                                {                                                                                /// <summary>                                                            /// Activity that volition exist invoked for any call to this Controller in social club to handle the current error                                                            /// </summary>                                                            /// <returns>A generic error formatted as JSON considering we are in a REST API app context</returns>                                                            [HttpGet]                                                                                [HttpPost]                                                                                [HttpHead]                                                                                [HttpDelete]                                                                                [HttpPut]                                                                                [HttpOptions]                                                                                [HttpPatch]                                                                                public                                                            JsonResult                                                            Handle                    ()                                                                                {                                                                                //Become the exception that has unsaid the call to this controller                                                            Exception                                                            exception                                                            =                                                            HttpContext                    .                    Features                    .                    Get                    <                    IExceptionHandlerFeature                    >()?.                    Mistake                    ;                                                                                //Log the exception via the content of the variable named "exception" if it is not NULL                                                            //...                                                            //We build a generic response with a JSON format considering we are in a REST API app context                                                            //Nosotros also add an HTTP response header to indicate to the client app that the response                                                            //is an error                                                            var                                                            responseBody                                                            =                                                            new                                                            Dictionary                    <                    String                    ,                                                            String                    >{                                                            {                                                                                "bulletin"                    ,                                                            "An error occur, please retry"                                                                                }                                                            };                                                                                JsonResult                                                            response                                                            =                                                            new                                                            JsonResult                    (                    responseBody                    );                                                                                //Notation that we're using an internal server error response                                                            //In some cases it may be prudent to render 4xx error codes, if nosotros accept misbehaving clients                                                            response                    .                    StatusCode                                                            =                                                            (                    int                    )                    HttpStatusCode                    .                    InternalServerError                    ;                                                                                Request                    .                    HttpContext                    .                    Response                    .                    Headers                    .                    Remove                    (                    "X-Fault"                    );                                                                                Request                    .                    HttpContext                    .                    Response                    .                    Headers                    .                    Add                    (                    "Ten-Mistake"                    ,                                                            "truthful"                    );                                                                                return                                                            response                    ;                                                                                }                                                                                }                                        }                                                      

Definition in the awarding Startup.cs file of the mapping of the exception handler to the dedicated error handling API controller:

                                                        using                                                            Microsoft.AspNetCore.Builder                    ;                                        using                                                            Microsoft.AspNetCore.Hosting                    ;                                        using                                                            Microsoft.AspNetCore.Mvc                    ;                                        using                                                            Microsoft.Extensions.Configuration                    ;                                        using                                                            Microsoft.Extensions.DependencyInjection                    ;                                        namespace                                                            MyProject                                        {                                                                                public                                                            grade                                                            Startup                                                                                {                                        ...                                                                                public                                                            void                                                            Configure                    (                    IApplicationBuilder                                                            app                    ,                                                            IHostingEnvironment                                                            env                    )                                                                                {                                                                                //First we configure the error handler middleware!                                                            //We enable the global error handler in others environments than DEV                                                            //because debug page are useful during implementation                                                            if                                                            (                    env                    .                    IsDevelopment                    ())                                                                                {                                                                                app                    .                    UseDeveloperExceptionPage                    ();                                                                                }                                                                                else                                                                                {                                                                                //Our global handler is defined on "/api/mistake" URL so we point to the                                                            //exception handler to call this API controller                                                            //on any unexpected exception raised by the awarding                                                            app                    .                    UseExceptionHandler                    (                    "/api/fault"                    );                                                                                //To customize the response content type and text, use the overload of                                                            //UseStatusCodePages that takes a content blazon and format string.                                                            app                    .                    UseStatusCodePages                    (                    "text/apparently"                    ,                                                            "Status lawmaking page, status code: {0}"                    );                                                                                }                                                                                //We configure others middlewares, recollect that the declaration order is important...                                                            app                    .                    UseMvc                    ();                                                                                //...                                                            }                                                                                }                                        }                                                      

References:

  • Exception handling with ASP.Net Core

ASP NET Web API web awarding¶

With ASP.NET Spider web API (from the standard .Net framework and not from the .NET Cadre framework), you tin define and register handlers in order to trace and handle any error that occurs in the application.

Definition of the handler for the tracing of the error details:

                                                        using                                                            System                    ;                                        using                                                            System.Spider web.Http.ExceptionHandling                    ;                                        namespace                                                            MyProject.Security                                        {                                                                                /// <summary>                                                            /// Global logger used to trace whatever error that occurs at application wide level                                                            /// </summary>                                                            public                                                            class                                                            GlobalErrorLogger                                                            :                                                            ExceptionLogger                                                                                {                                                                                /// <summary>                                                            /// Method in charge of the management of the mistake from a tracing signal of view                                                            /// </summary>                                                            /// <param name="context">Context containing the error details</param>                                                            public                                                            override                                                            void                                                            Log                    (                    ExceptionLoggerContext                                                            context                    )                                                                                {                                                                                //Get the exception                                                            Exception                                                            exception                                                            =                                                            context                    .                    Exception                    ;                                                                                //Log the exception via the content of the variable named "exception" if information technology is not Aught                                                            //...                                                            }                                                                                }                                        }                                                      

Definition of the handler for the management of the error in order to return a generic response:

                                                        using                                                            Newtonsoft.Json                    ;                                        using                                                            System                    ;                                        using                                                            System.Collections.Generic                    ;                                        using                                                            System.Net                    ;                                        using                                                            System.Net.Http                    ;                                        using                                                            System.Text                    ;                                        using                                                            System.Threading                    ;                                        using                                                            Organisation.Threading.Tasks                    ;                                        using                                                            Organisation.Web.Http                    ;                                        using                                                            System.Web.Http.ExceptionHandling                    ;                                        namespace                                                            MyProject.Security                                        {                                                                                /// <summary>                                                            /// Global handler used to handle any error that occurs at application broad level                                                            /// </summary>                                                            public                                                            grade                                                            GlobalErrorHandler                                                            :                                                            ExceptionHandler                                                                                {                                                                                /// <summary>                                                            /// Method in accuse of handle the generic response transport in example of error                                                            /// </summary>                                                            /// <param proper name="context">Error context</param>                                                            public                                                            override                                                            void                                                            Handle                    (                    ExceptionHandlerContext                                                            context                    )                                                                                {                                                                                context                    .                    Result                                                            =                                                            new                                                            GenericResult                    ();                                                                                }                                                                                /// <summary>                                                            /// Grade used to represent the generic response send                                                            /// </summary>                                                            private                                                            class                                                            GenericResult                                                            :                                                            IHttpActionResult                                                                                {                                                                                /// <summary>                                                            /// Method in charge of creating the generic response                                                            /// </summary>                                                            /// <param name="cancellationToken">Object to abolish the chore</param>                                                            /// <returns>A task in accuse of sending the generic response</returns>                                                            public                                                            Chore                    <                    HttpResponseMessage                    >                                                            ExecuteAsync                    (                    CancellationToken                                                            cancellationToken                    )                                                                                {                                                                                //Nosotros build a generic response with a JSON format because nosotros are in a Remainder API app context                                                            //Nosotros besides add together an HTTP response header to signal to the customer app that the response                                                            //is an fault                                                            var                                                            responseBody                                                            =                                                            new                                                            Dictionary                    <                    Cord                    ,                                                            String                    >{                                                            {                                                                                "message"                    ,                                                            "An mistake occur, please retry"                                                                                }                                                            };                                                                                // Note that we're using an internal server error response                                                            // In some cases information technology may be prudent to return 4xx fault codes, if we have misbehaving clients                                                                                HttpResponseMessage                                                            response                                                            =                                                            new                                                            HttpResponseMessage                    (                    HttpStatusCode                    .                    InternalServerError                    );                                                                                response                    .                    Headers                    .                    Add                    (                    "X-Error"                    ,                                                            "true"                    );                                                                                response                    .                    Content                                                            =                                                            new                                                            StringContent                    (                    JsonConvert                    .                    SerializeObject                    (                    responseBody                    ),                                                                                Encoding                    .                    UTF8                    ,                                                            "application/json"                    );                                                                                return                                                            Task                    .                    FromResult                    (                    response                    );                                                                                }                                                                                }                                                                                }                                        }                                                      

Registration of the both handlers in the application WebApiConfig.cs file:

                                                        using                                                            MyProject.Security                    ;                                        using                                                            Organization.Spider web.Http                    ;                                        using                                                            Organisation.Web.Http.ExceptionHandling                    ;                                        namespace                                                            MyProject                                        {                                                                                public                                                            static                                                            form                                                            WebApiConfig                                                                                {                                                                                public                                                            static                                                            void                                                            Register                    (                    HttpConfiguration                                                            config                    )                                                                                {                                                                                //Register global error logging and treatment handlers in first                                                            config                    .                    Services                    .                    Replace                    (                    typeof                    (                    IExceptionLogger                    ),                                                            new                                                            GlobalErrorLogger                    ());                                                                                config                    .                    Services                    .                    Supplant                    (                    typeof                    (                    IExceptionHandler                    ),                                                            new                                                            GlobalErrorHandler                    ());                                                                                //Remainder of the configuration                                                            //...                                                            }                                                                                }                                        }                                                      

Setting customErrors section to the Spider web.config file inside the csharp <organisation.spider web> node as follows.

                                                        <                    configuration                    >                                                                                ...                                                                                <                    system                    .                    spider web                    >                                                                                <                    customErrors                                                            mode                    =                    "RemoteOnly"                                                                                defaultRedirect                    =                    "~/ErrorPages/Oops.aspx"                                                            />                                                                                ...                                                                                </                    system                    .                    web                    >                                        </                    configuration                    >                                                      

References:

  • Exception handling with ASP.Net Web API

  • ASP.NET Error Treatment

Sources of the prototype¶

The source code of all the sandbox projects created to find the correct setup to use is stored in this GitHub repository.

Appendix HTTP Errors¶

A reference for HTTP errors tin can be found here RFC 2616. Using fault messages that do not provide implementation details is important to avoid information leakage. In general, consider using 4xx fault codes for requests that are due to an fault on the role of the HTTP client (e.m. unauthorized access, request body likewise large) and apply 5xx to betoken errors that are triggered on server side, due to an unforeseen problems. Ensure that applications are monitored for 5xx errors which are a good indication of the application failing for some sets of inputs.

ollievess1942.blogspot.com

Source: https://cheatsheetseries.owasp.org/cheatsheets/Error_Handling_Cheat_Sheet.html

0 Response to "According the Owasp Code Review Guide Why Is Error Handling Important"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel