Introduction

Error handling is a part of the overall security of an application. Except in movies, an attack always begins with a Reconnaissance phase in which the attacker will try to gather as much technical information (often name and version properties) as 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 attack.

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

Context

Issues at the error handling level can reveal a lot of information about the target and can also be used to identify injection points in the target's features.

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

  1. HTTP Status 500 - For input string: "null"
  2. type Exception report
  3. message For input string: "null"
  4. description The server encountered an internal error that prevented it from fulfilling this request.
  5. exception
  6. java.lang.NumberFormatException: For input string: "null"
  7. java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  8. java.lang.Integer.parseInt(Integer.java:492)
  9. java.lang.Integer.parseInt(Integer.java:527)
  10. sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  11. sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  12. sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  13. java.lang.reflect.Method.invoke(Method.java:606)
  14. com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
  15. com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
  16. com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
  17. org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
  18. com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
  19. ...
  20. note: The full stack trace of the root cause is available in the Apache Tomcat/7.0.56 logs.

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

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

The OWASP Testing Guide provides different techniques to obtain technical information from an application.

Objective

The article shows how to configure a global error handler at the configuration level when possible, otherwise at code level, in different technologies, in order to ensure that if an unexpected error occurs then a generic response is returned by the application but the error is traced on server side for investigation.

The following schema shows the target approach:

Overview

As most recent application topologies are API based, we assume in this article that the backend exposes only a REST API and does not contain any user interface content.

For the error logging operation itself, the logging cheat sheet should be used. This article focuses on the error handling part.

Proposition

For each technology, a setup will be proposed with configuration and code snippet.

Java classic web application

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

We propose here a configuration that can be used from Servlet specification version 2.5 and above.

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:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ns="http://java.sun.com/xml/ns/javaee"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  4. version="3.0">
  5. ...
  6. <error-page>
  7. <exception-type>java.lang.Exception</exception-type>
  8. <location>/error.jsp</location>
  9. </error-page>
  10. ...
  11. </web-app>

Content of the error.jsp file:

  1. <%@ page language="java" isErrorPage="true" contentType="application/json; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%
  4. String errorMessage = exception.getMessage();
  5. //Log the exception via the content of the implicit variable named "exception"
  6. //...
  7. //We build a generic response with a JSON format because we are in a REST API app context
  8. //We also add an HTTP response header to indicate to the client app that the response is an error
  9. response.setHeader("X-ERROR", "true");
  10. response.setStatus(200);
  11. %>
  12. {"message":"An error occur, please retry"}

Java SpringMVC/SpringBoot web application

With SpringMVC or SpringBoot, you can define a global error handler by simply implementing the following kind of class in your project.

We indicate to the handler, via the annotation @ExceptionHandler, to act when any exception extending the class java.lang.Exception is thrown by the application.

  1. import net.minidev.json.JSONObject;
  2. import org.springframework.http.HttpHeaders;
  3. import org.springframework.http.HttpStatus;
  4. import org.springframework.http.MediaType;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.web.bind.annotation.ControllerAdvice;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.context.request.WebRequest;
  9. /**
  10. * Global error handler in charge of returning a generic response in case of unexpected error situation.
  11. */
  12. @ControllerAdvice
  13. public class RestResponseEntityExceptionHandler {
  14. @ExceptionHandler(value = {Exception.class})
  15. public ResponseEntity<Object> handleGlobalError(RuntimeException exception, WebRequest request) {
  16. //Log the exception via the content of the parameter named "exception"
  17. //...
  18. //We build a generic response with a JSON format because we are in a REST API app context
  19. //We also add an HTTP response header to indicate to the client app that the response is an error
  20. HttpHeaders responseHeaders = new HttpHeaders();
  21. responseHeaders.setContentType(MediaType.APPLICATION_JSON);
  22. responseHeaders.set("X-ERROR", "true");
  23. JSONObject responseBody = new JSONObject();
  24. responseBody.put("message", "An error occur, please retry");
  25. ResponseEntity<JSONObject> response = new ResponseEntity<>(responseBody, responseHeaders,
  26. HttpStatus.OK);
  27. return (ResponseEntity) response;
  28. }
  29. }

References:

ASP NET Core web application

With ASP.NET Core, you can define a global error handler by indicating that the exception handler is a dedicated API Controller.

Content of the API Controller dedicated to the error handling:

  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Diagnostics;
  3. using Microsoft.AspNetCore.Mvc;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Net;
  7. namespace MyProject.Controllers
  8. {
  9. /// <summary>
  10. /// API Controller used to intercept and handle all unexpected exception
  11. /// </summary>
  12. [Route("api/[controller]")]
  13. [ApiController]
  14. [AllowAnonymous]
  15. public class ErrorController : ControllerBase
  16. {
  17. /// <summary>
  18. /// Action that will be invoked for any call to this Controller in order to handle the current error
  19. /// </summary>
  20. /// <returns>A generic error formatted as JSON because we are in a REST API app context</returns>
  21. [HttpGet]
  22. [HttpPost]
  23. [HttpHead]
  24. [HttpDelete]
  25. [HttpPut]
  26. [HttpOptions]
  27. [HttpPatch]
  28. public JsonResult Handle()
  29. {
  30. //Get the exception that has implied the call to this controller
  31. Exception exception = HttpContext.Features.Get<IExceptionHandlerFeature>()?.Error;
  32. //Log the exception via the content of the variable named "exception" if it is not NULL
  33. //...
  34. //We build a generic response with a JSON format because we are in a REST API app context
  35. //We also add an HTTP response header to indicate to the client app that the response
  36. //is an error
  37. var responseBody = new Dictionary<String, String>{ {
  38. "message", "An error occur, please retry"
  39. } };
  40. JsonResult response = new JsonResult(responseBody);
  41. response.StatusCode = (int)HttpStatusCode.OK;
  42. Request.HttpContext.Response.Headers.Remove("X-ERROR");
  43. Request.HttpContext.Response.Headers.Add("X-ERROR", "true");
  44. return response;
  45. }
  46. }
  47. }

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

  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. namespace MyProject
  7. {
  8. public class Startup
  9. {
  10. ...
  11. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  12. {
  13. //First we configure the error handler middleware!
  14. //We enable the global error handler in others environments than DEV
  15. //because debug page are useful during implementation
  16. if (env.IsDevelopment())
  17. {
  18. app.UseDeveloperExceptionPage();
  19. }
  20. else
  21. {
  22. //Our global handler is defined on "/api/error" URL so we indicate to the
  23. //exception handler to call this API controller
  24. //on any unexpected exception raised by the application
  25. app.UseExceptionHandler("/api/error");
  26. }
  27. //We configure others middlewares, remember that the declaration order is important...
  28. app.UseMvc();
  29. //...
  30. }
  31. }
  32. }

References:

ASP NET Web API web application

With ASP.NET Web API (from the standard .NET framework and not from the .NET Core framework), you can 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:

  1. using System;
  2. using System.Web.Http.ExceptionHandling;
  3. namespace MyProject.Security
  4. {
  5. /// <summary>
  6. /// Global logger used to trace any error that occurs at application wide level
  7. /// </summary>
  8. public class GlobalErrorLogger : ExceptionLogger
  9. {
  10. /// <summary>
  11. /// Method in charge of the management of the error from a tracing point of view
  12. /// </summary>
  13. /// <param name="context">Context containing the error details</param>
  14. public override void Log(ExceptionLoggerContext context)
  15. {
  16. //Get the exception
  17. Exception exception = context.Exception;
  18. //Log the exception via the content of the variable named "exception" if it is not NULL
  19. //...
  20. }
  21. }
  22. }

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 System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;

namespace MyProject.Security
{
    /// <summary>
    /// Global handler used to handle any error that occurs at application wide level
    /// </summary>
    public class GlobalErrorHandler : ExceptionHandler
    {
        /// <summary>
        /// Method in charge of handle the generic response send in case of error
        /// </summary>
        /// <param name="context">Error context</param>
        public override void Handle(ExceptionHandlerContext context)
        {
            context.Result = new GenericResult();
        }

        /// <summary>
        /// Class 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 cancel the task</param>
            /// <returns>A task in charge of sending the generic response</returns>
            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                //We build a generic response with a JSON format because we are in a REST API app context
                //We also add an HTTP response header to indicate to the client app that the response 
                //is an error
                var responseBody = new Dictionary<String, String>{ {
                    "message", "An error occur, please retry"
                } };
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                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 System.Web.Http;
using System.Web.Http.ExceptionHandling;

namespace MyProject
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //Register global error logging and handling handlers in first
            config.Services.Replace(typeof(IExceptionLogger), new GlobalErrorLogger());
            config.Services.Replace(typeof(IExceptionHandler), new GlobalErrorHandler());
            //Rest of the configuration
            //...
        }
    }
}

References:

Sources of the prototype

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