Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions dojo/api.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
# see tastypie documentation at http://django-tastypie.readthedocs.org/en
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.http import HttpResponse
from django.urls import resolve, get_script_prefix
import base64
from tastypie import fields
from tastypie import http
from tastypie.fields import RelatedField
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from tastypie.authorization import DjangoAuthorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.exceptions import Unauthorized, ImmediateHttpResponse, NotFound
from tastypie.http import HttpCreated
from tastypie.resources import ModelResource, Resource
from tastypie.resources import ModelResource, Resource, sanitize
from tastypie.serializers import Serializer
from tastypie.validation import FormValidation, Validation
from tastypie.exceptions import BadRequest
from django.urls.exceptions import Resolver404
from django.utils import timezone
from django.db.models import Count, Q

from django.conf import settings
from django.utils.cache import patch_cache_control, patch_vary_headers
from django.views.decorators.csrf import csrf_exempt
from dojo.models import Product, Engagement, Test, Finding, \
User, ScanSettings, IPScan, Scan, Stub_Finding, Risk_Acceptance, \
Finding_Template, Test_Type, Development_Environment, \
Expand Down Expand Up @@ -90,6 +95,78 @@ def form_args(self, bundle):


class BaseModelResource(ModelResource):

def wrap_view(self, view):
"""
Wraps views to check if APIv1 is enabled
"""
@csrf_exempt
def wrapper(request, *args, **kwargs):
try:
api_v1_deprecation_warning = 'APIv1 is deprecated and may contain vulnerabilities. It is disabled by default. '
if not settings.LEGACY_API_V1_ENABLE:
raise BadRequest({'code': 666, 'message': api_v1_deprecation_warning + 'It can be enabled at your own risk by setting DD_LEGACY_API_V1_ENABLE to True, or by setting LEGACY_API_V1_ENABLE to True in settings(.dist).py or local_settings.py. APIv1 will be removed at 2021-06-30'})

callback = getattr(self, view)
response = callback(request, *args, **kwargs)

# Our response can vary based on a number of factors, use
# the cache class to determine what we should ``Vary`` on so
# caches won't return the wrong (cached) version.
varies = getattr(self._meta.cache, "varies", [])

if varies:
patch_vary_headers(response, varies)

if self._meta.cache.cacheable(request, response):
if self._meta.cache.cache_control():
# If the request is cacheable and we have a
# ``Cache-Control`` available then patch the header.
patch_cache_control(response, **self._meta.cache.cache_control())

if request.is_ajax() and not response.has_header("Cache-Control"):
# IE excessively caches XMLHttpRequests, so we're disabling
# the browser cache here.
# See http://www.enhanceie.com/ie/bugs.asp for details.
patch_cache_control(response, no_cache=True)

# official header for deprecation
response['Deprecation'] = 'true'

# official header for warning (666 is not official)
response['Warning'] = '666 APIv1 ' + api_v1_deprecation_warning + 'At your own or your admins risk it has been enabled. APIv1 will be removed at 2021-06-30'

return response
except (BadRequest, fields.ApiFieldError) as e:
data = {"error": sanitize(e.args[0]) if getattr(e, 'args') else ''}
return self.error_response(request, data, response_class=http.HttpBadRequest)
except ValidationError as e:
data = {"error": sanitize(e.messages)}
return self.error_response(request, data, response_class=http.HttpBadRequest)
except Exception as e:
# Prevent muting non-django's exceptions
# i.e. RequestException from 'requests' library
if hasattr(e, 'response') and isinstance(e.response, HttpResponse):
return e.response

# A real, non-expected exception.
# Handle the case where the full traceback is more helpful
# than the serialized error.
if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
raise

# Re-raise the error to get a proper traceback when the error
# happend during a test case
if request.META.get('SERVER_NAME') == 'testserver':
raise

# Rather than re-raising, we're going to things similar to
# what Django does. The difference is returning a serialized
# error message.
return self._handle_500(request, e)

return wrapper

@classmethod
def get_fields(cls, fields=None, excludes=None):
"""
Expand Down
6 changes: 5 additions & 1 deletion dojo/settings/settings.dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@
# when enabled in sytem settings, every minute a job run to delete excess duplicates
# we limit the amount of duplicates that can be deleted in a single run of that job
# to prevent overlapping runs of that job from occurrring
DD_DUPE_DELETE_MAX_PER_RUN=(int, 200)
DD_DUPE_DELETE_MAX_PER_RUN=(int, 200),
# APIv1 is depreacted and will be removed at 2021-06-30
DD_LEGACY_API_V1_ENABLE=(bool, False),
)


Expand Down Expand Up @@ -463,6 +465,8 @@ def generate_url(scheme, double_slashes, user, password, host, port, path, param
r'empty_questionnaire/([\d]+)/answer'
)

LEGACY_API_V1_ENABLE = env('DD_LEGACY_API_V1_ENABLE')

# ------------------------------------------------------------------------------
# SECURITY DIRECTIVES
# ------------------------------------------------------------------------------
Expand Down
29 changes: 28 additions & 1 deletion dojo/unittests/test_api_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
from unittest import skip

from django.contrib.auth.models import User
from django.test import TestCase
from django.test import TestCase, override_settings
from tastypie.models import ApiKey
from tastypie.test import ResourceTestCaseMixin

from dojo.models import Product, Engagement, Product_Type


@override_settings(LEGACY_API_V1_ENABLE=True)
class ApiBasicOperationsTest(ResourceTestCaseMixin, TestCase):
def setUp(self):
super(ApiBasicOperationsTest, self).setUp()
Expand Down Expand Up @@ -141,3 +142,29 @@ def test_inclomplete_creation_request(self):
'engagements': {'status': ['This field is required.'],
'target_end': ['This field is required.'],
'target_start': ['This field is required.']}})


@override_settings(LEGACY_API_V1_ENABLE=False)
class ApiV1Disabled(ResourceTestCaseMixin, TestCase):
def setUp(self):
super(ApiV1Disabled, self).setUp()
self.username = 'test_user'
self.password = 'p4ss'
self.user = User.objects.create_user(self.username, 'user@mail.com',
self.password, is_active=True,
is_staff=True, is_superuser=True)
self.api_key = ApiKey.objects.create(user=self.user)

self.prod_type = Product_Type.objects.create(name='WebApp')

def get_credentials(self):
return self.create_apikey(self.username, self.user.api_key.key)

def test_api_v1_disabled(self):
r = self.api_client.get('/api/v1/products/',
authentication=self.get_credentials())

self.assertHttpBadRequest(r)
data = self.deserialize(r)
print(data)
self.assertTrue('666' in str(data))