Stack trace exposure

Internal stack traces included in client responses

Description

A Java exception trace in an HTTP response reveals which classes and methods handled the request.

Potential impact

Traces may expose file paths, hostnames, configuration values and clues about library versions. This information can reveal weaknesses in a deployment.

Remediation

  • Handle exceptions in one place, such as a Servlet Filter, Spring @ControllerAdvice or a JAX-RS ExceptionMapper. Return an appropriate status and a short message. Record the exception in restricted server logs with a retention limit.
  • Configure a production error page and check the response for class names, paths, SQL and configuration values. For Spring Boot’s built-in error response, use server.error.include-stacktrace=never in 3.5 or spring.web.error.include-stacktrace=never in 4.0.

Examples

Before

java
import javax.servlet.http.*;
import java.io.IOException;

public class ErrorEchoServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String v = req.getParameter("div");
            if (v != null) {
                int n = Integer.parseInt(v);
                int r = 100 / n; // 0 입력 시 예외 발생 가능
                resp.getWriter().println("result=" + r);
            }
        } catch (Exception ex) {
            // BAD: 스택 트레이스를 사용자 응답에 직접 출력
            ex.printStackTrace(resp.getWriter());
        }
    }
}

After

java
import javax.servlet.http.*;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.*;

public class ErrorSafeServlet extends HttpServlet {
    private static final Logger LOG = Logger.getLogger(ErrorSafeServlet.class.getName());

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String v = req.getParameter("div");
            if (v != null) {
                int n = Integer.parseInt(v);
                int r = 100 / n;
                resp.getWriter().println("ok");
                return;
            }
            resp.getWriter().println("ok");
        } catch (Exception ex) {
            String errorId = UUID.randomUUID().toString();
            // 서버 로그에만 상세 스택 트레이스 기록
            LOG.log(Level.SEVERE, "Unhandled exception, errorId=" + errorId, ex);
            // 사용자에게는 일반화된 오류 메시지 전송
            resp.resetBuffer();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "요청 처리 중 오류가 발생했습니다. (id=" + errorId + ")");
        }
    }
}

ex.printStackTrace(resp.getWriter()) writes the exception trace to the client. On an exception, the revised servlet logs a generated error ID and passes it to sendError in the HTTP 500 message. If the error page displays that ID, support can use it to find the server log entry.

References