Traceability loss - Python

Traceability loss - Python

Need

Improved traceability and logging capabilities

Context

  • Usage of Python 3 for developing Python applications
  • Usage of Django for building web applications

Description

Non compliant code

        from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request, *args, **kwargs):
        try:
            # Some critical action that can raise an exception
            1 / 0
        except:
            return HttpResponse('An error occurred', status=500)

        
        

This code represents a Django view that handles GET requests. The critical action in this case is a division by zero, which will always raise a ZeroDivisionError.

The vulnerability here is that the exception is caught and handled, but there is no logging or tracking of this error event. This means that if this error occurs, there would be no trace of it in the system logs, making it impossible to detect and debug any potential security events related to this error.

The except block simply returns a HTTP response with a status code of 500 and a generic error message, providing no information about the nature of the error or where in the code it occurred. This lack of traceability makes it difficult to identify and fix the underlying issue, which could potentially be a security vulnerability.

Moreover, the use of a bare except clause is a bad practice as it catches all types of exceptions including those which are not meant to be caught and handled at this level, such as SystemExit and KeyboardInterrupt. This can make debugging difficult and can also hide other potentially serious issues.

Steps

  • Implement a logging system to record all errors and exceptions that occur during the execution of the application.
  • In the catch block, instead of simply returning a response, log the exception details including the type, message, and stack trace.
  • Ensure that the logging system is secure and that only authorized personnel can access the logs.
  • Consider using a centralized logging system to aggregate logs from different parts of the application, making it easier to monitor and analyze them.
  • Regularly review the logs to identify any unusual or suspicious activity.

Compliant code

        import logging
from django.http import HttpResponse
from django.views import View

# Create a custom logger
logger = logging.getLogger(__name__)

class MyView(View):
    def get(self, request, *args, **kwargs):
        try:
            # Some critical action that can raise an exception
            1 / 0
        except Exception as e:
            # Log the exception
            logger.error(f'An error occurred: {e}', exc_info=True)
            return HttpResponse('An error occurred', status=500)
        
        

The updated code includes a logging system to record all errors and exceptions that occur during the execution of the application.

In the try block, we have a critical action that can potentially raise an exception. If an exception is raised, it is caught in the except block.

Instead of simply returning a response, we now log the exception details using the logger.error() method. The exc_info=True argument ensures that the exception type, message, and stack trace are included in the log.

The logger is created using logging.getLogger(__name__), which creates a logger with the same name as the module. This allows us to control the logging level and handlers on a per-module basis.

This logging system helps to maintain traceability in the application by ensuring that all errors and exceptional events are properly recorded. It is important to ensure that the logging system is secure and that only authorized personnel can access the logs.

Consider using a centralized logging system to aggregate logs from different parts of the application, making it easier to monitor and analyze them. Regularly review the logs to identify any unusual or suspicious activity.

References