Django Missing Permissions Check
ID |
python.django_missing_permissions_check |
Severity |
high |
Resource |
Access Control |
Language |
Python |
Tags |
CWE:280, NIST.SP.800-53, OWASP:2021:A4, PCI-DSS:6.5.6, django |
Description
Improper handling of object-level permissions within a Django application may lead to unauthorized access.
Rationale
In Django applications, object-level permissions are crucial to ensure that users can only access or modify data they are authorized to interact with. Failing to enforce these permissions appropriately can expose sensitive data or lead to unauthorized actions being performed.
This vulnerability typically arises when user requests are not adequately checked against the permissions set on the data objects being accessed.
from django.views.generic import DetailView
from myapp.models import MyModel
class MyDetailView(DetailView):
model = MyModel
def get_object(self): # FLAW
obj = super().get_object()
# Missing permission check
return obj
In the example above, the view retrieves an object from the database without checking if the current user has the necessary permissions to access it.
Remediation
To remediate this vulnerability, implement a check for object-level permissions using Django’s permission system before accessing the object. This can be done by overriding the get_object
method and raising an appropriate exception if the user does not have the required permission.
from django.core.exceptions import PermissionDenied
from django.views.generic import DetailView
from myapp.models import MyModel
class MyDetailView(DetailView):
model = MyModel
def get_object(self):
obj = super().get_object()
if not self.request.user.has_perm('myapp.view_mymodel', obj):
raise PermissionDenied("You do not have permission to view this object.")
return obj
By adding a permission check that uses the has_perm
method, you help ensure that users cannot access or modify data without the necessary permissions. This implementation enhances security by controlling access at the object level based on user permissions.
For Django REST Framework, ensure to call check_object_permissions
within the get_object
method:
from rest_framework import generics
from myapp.models import MyModel
from myapp.serializers import MyModelSerializer
class MyDetailAPIView(generics.RetrieveAPIView):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
def get_object(self):
obj = super().get_object()
self.check_object_permissions(self.request, obj)
return obj
References
-
CWE-280: Improper Handling of Insufficient Permissions or Privileges.