Python django.core.exceptions.SuspiciousOperation() Examples
The following are 30
code examples of django.core.exceptions.SuspiciousOperation().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.core.exceptions
, or try the search function
.
Example #1
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 7 votes |
def decode(self, session_data): encoded_data = base64.b64decode(force_bytes(session_data)) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousSession("Session data corrupted") else: return self.serializer().loads(serialized) except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(force_text(e)) return {}
Example #2
Source File: base.py From python2017 with MIT License | 6 votes |
def decode(self, session_data): encoded_data = base64.b64decode(force_bytes(session_data)) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousSession("Session data corrupted") else: return self.serializer().loads(serialized) except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(force_text(e)) return {}
Example #3
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def decide_invitation(request, invite_id): invite = get_object_or_404(TeamRequest, pk=invite_id) team = invite.team if team.owner_id is None or team.owner_id != request.user.id: raise SuspiciousOperation(_('User is not the owner of the team')) elif 'accept' in request.POST: invite.team.members.add(invite.invitee) invite.team.save() notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee) messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username)) elif 'reject' in request.POST: notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee) messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username)) else: return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject')) invite.delete() return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
Example #4
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def invite_members(request, team_id): """Return a team edit view, or handle the form submission.""" team = get_object_or_404(Team, pk=team_id) if team.owner_id is None or team.owner_id != request.user.id: raise SuspiciousOperation(_('User is not the owner of the team')) if request.method == 'POST': form = TeamInviteForm(request.POST, team=team) if form.is_valid(): to_invite = form.cleaned_data['members'] invites = [TeamRequest(team=team, inviter=request.user, invitee=x) for x in to_invite] TeamRequest.objects.bulk_create(invites) for user in to_invite: notify.send(request.user, recipient=user, actor=request.user, verb='invite', action_object=team, target=user) messages.success(request, _('Invited {count} members to the team').format(count=len(to_invite))) return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) else: form = TeamInviteForm(team=team) return render(request, 'teams/invite.html', context={ 'team': team, 'form': form })
Example #5
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def edit_team(request, team_id): """Return a team edit view, or handle the form submission.""" # TODO: if user turns off invitation-required, let everyone in who had outstanding membership requests team = get_object_or_404(Team, pk=team_id) if team.owner_id is None or team.owner_id != request.user.id: raise SuspiciousOperation(_('User is not the owner of the team')) if request.method == 'POST': form = TeamCreateForm(request.POST, instance=team) if form.is_valid(): form.save() messages.success(request, _('Updated team information')) return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) else: form = TeamCreateForm(instance=team) return render(request, 'teams/edit_team.html', context={ 'team': team, 'form': form })
Example #6
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def revoke_membership(request, team_id, member_id): team = get_object_or_404(Team, pk=team_id) user = get_object_or_404(User, pk=member_id) if team.owner_id is None or team.owner_id != request.user.id: raise SuspiciousOperation(_('User is not the owner of the team')) elif user == team.owner: raise SuspiciousOperation(_('Cannot remove the owner from the team')) elif not team.invitation_required: raise SuspiciousOperation(_('Cannot remove user from teams that don\'t require an invitation')) team.members.remove(user) team.save() notify.send(request.user, recipient=user, actor=request.user, verb='remove', action_object=team, target=user) messages.success(request, _('Removed {name} from team').format(name=user.username)) return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
Example #7
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def join_team(request, team_id): team = get_object_or_404(Team, pk=team_id) if team.members.filter(id=request.user.id).exists(): raise SuspiciousOperation(_('User is already a member of the team')) elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required: team.members.add(request.user) team.save() TeamRequest.objects.filter(invitee=request.user, team=team).delete() messages.success(request, _('Joined team {name}').format(name=team.name)) return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) elif TeamRequest.objects.filter(invitee=request.user, team=team).exists(): return HttpResponseBadRequest(_('User already has a membership request with the team')) else: TeamRequest.objects.create(invitee=request.user, team=team) if team.owner: notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team) messages.success(request, _('Requested invitation to team {name}').format(name=team.name)) return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
Example #8
Source File: storage.py From dingtalk-django-example with GNU General Public License v3.0 | 6 votes |
def _normalize_name(self, name): """ Normalizes the name so that paths like /path/to/ignored/../foo.txt work. We check to make sure that the path pointed to is not outside the directory specified by the LOCATION setting. """ if name.startswith("https://") or name.startswith("http://"): return name base_path = force_text(self.location) base_path = base_path.rstrip('/') final_path = urljoin(base_path.rstrip('/') + "/", name) base_path_len = len(base_path) if (not final_path.startswith(base_path) or final_path[base_path_len:base_path_len + 1] not in ('', '/')): raise SuspiciousOperation("Attempted access to '%s' denied." % name) return final_path.lstrip('/')
Example #9
Source File: common.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def skip_suspicious_operations(record): """Prevent django from sending 500 error email notifications for SuspiciousOperation events, since they are not true server errors, especially when related to the ALLOWED_HOSTS configuration background and more information: http://www.tiwoc.de/blog/2013/03/django-prevent-email-notification-on-susp\ iciousoperation/ """ if record.exc_info: exc_value = record.exc_info[1] if isinstance(exc_value, SuspiciousOperation): return False return True # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration.
Example #10
Source File: authentication.py From timed-backend with GNU Affero General Public License v3.0 | 6 votes |
def get_userinfo_or_introspection(self, access_token): try: claims = self.cached_request( self.get_userinfo, access_token, "auth.userinfo" ) except requests.HTTPError as e: if not ( e.response.status_code in [401, 403] and settings.OIDC_CHECK_INTROSPECT ): raise e # check introspection if userinfo fails (confidental client) claims = self.cached_request( self.get_introspection, access_token, "auth.introspection" ) if "client_id" not in claims: raise SuspiciousOperation("client_id not present in introspection") return claims
Example #11
Source File: base.py From bioforum with MIT License | 6 votes |
def decode(self, session_data): encoded_data = base64.b64decode(force_bytes(session_data)) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousSession("Session data corrupted") else: return self.serializer().loads(serialized) except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(str(e)) return {}
Example #12
Source File: file.py From bioforum with MIT License | 6 votes |
def load(self): session_data = {} try: with open(self._key_to_file(), "rb") as session_file: file_data = session_file.read() # Don't fail if there is no data in the session file. # We may have opened the empty placeholder file. if file_data: try: session_data = self.decode(file_data) except (EOFError, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(str(e)) self.create() # Remove expired sessions. expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data)) if expiry_age <= 0: session_data = {} self.delete() self.create() except (IOError, SuspiciousOperation): self._session_key = None return session_data
Example #13
Source File: cached_db.py From bioforum with MIT License | 6 votes |
def load(self): try: data = self._cache.get(self.cache_key) except Exception: # Some backends (e.g. memcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. data = None if data is None: # Duplicate DBStore.load, because we need to keep track # of the expiry date to set it properly in the cache. try: s = self.model.objects.get( session_key=self.session_key, expire_date__gt=timezone.now() ) data = self.decode(s.session_data) self._cache.set(self.cache_key, data, self.get_expiry_age(expiry=s.expire_date)) except (self.model.DoesNotExist, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(str(e)) self._session_key = None data = {} return data
Example #14
Source File: test_auth.py From mozilla-django-oidc with Mozilla Public License 2.0 | 6 votes |
def test_allowed_unsecured_invalid_token(self): """Test payload data from invalid secure token (unsecured allowed).""" header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'})) payload = force_bytes(json.dumps({'foo': 'bar'})) # Compute signature key = b'mysupersecuretestkey' fake_key = b'mysupersecurefaketestkey' h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend()) msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload))) h.update(force_bytes(msg)) signature = b64encode(h.finalize()) token = '{}.{}.{}'.format( smart_text(b64encode(header)), smart_text(b64encode(payload)), smart_text(signature) ) token_bytes = force_bytes(token) key_text = smart_text(fake_key) with self.assertRaises(SuspiciousOperation) as ctx: self.backend.get_payload_data(token_bytes, key_text) self.assertEqual(ctx.exception.args[0], 'JWS token verification failed.')
Example #15
Source File: test_views.py From mozilla-django-oidc with Mozilla Public License 2.0 | 6 votes |
def test_get_auth_failure_tampered_session_state(self): """Test authentication failure attempt for an inactive user.""" user = User.objects.create_user('example_username') user.is_active = False user.save() get_data = { 'code': 'example_code', 'state': 'example_state' } url = reverse('oidc_authentication_callback') request = self.factory.get(url, get_data) request.session = { 'oidc_state': 'tampered_state' } callback_view = views.OIDCAuthenticationCallbackView.as_view() with self.assertRaises(SuspiciousOperation) as context: callback_view(request) expected_error_message = 'Session `oidc_state` does not match the OIDC callback state' self.assertEqual(context.exception.args, (expected_error_message,))
Example #16
Source File: base.py From openhgsenti with Apache License 2.0 | 6 votes |
def decode(self, session_data): encoded_data = base64.b64decode(force_bytes(session_data)) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousSession("Session data corrupted") else: return self.serializer().loads(serialized) except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(force_text(e)) return {}
Example #17
Source File: multipartparser.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def _update_unget_history(self, num_bytes): """ Updates the unget history as a sanity check to see if we've pushed back the same number of bytes in one chunk. If we keep ungetting the same number of bytes many times (here, 50), we're mostly likely in an infinite loop of some sort. This is usually caused by a maliciously-malformed MIME request. """ self._unget_history = [num_bytes] + self._unget_history[:49] number_equal = len([current_number for current_number in self._unget_history if current_number == num_bytes]) if number_equal > 40: raise SuspiciousOperation( "The multipart parser got stuck, which shouldn't happen with" " normal uploaded files. Check for malicious upload activity;" " if there is none, report this to the Django developers." )
Example #18
Source File: request.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def get_host(self): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in self.META): host = self.META['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in self.META: host = self.META['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = self.META['SERVER_NAME'] server_port = str(self.META['SERVER_PORT']) if server_port != ('443' if self.is_secure() else '80'): host = '%s:%s' % (host, server_port) allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS if validate_host(host, allowed_hosts): return host else: raise SuspiciousOperation( "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host)
Example #19
Source File: file.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def load(self): session_data = {} try: with open(self._key_to_file(), "rb") as session_file: file_data = session_file.read() # Don't fail if there is no data in the session file. # We may have opened the empty placeholder file. if file_data: try: session_data = self.decode(file_data) except (EOFError, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(str(e)) self.create() # Remove expired sessions. expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data)) if expiry_age <= 0: session_data = {} self.delete() self.create() except (IOError, SuspiciousOperation): self._session_key = None return session_data
Example #20
Source File: base.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def decode(self, session_data): encoded_data = base64.b64decode(force_bytes(session_data)) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousSession("Session data corrupted") else: return self.serializer().loads(serialized) except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(str(e)) return {}
Example #21
Source File: db.py From acacia_main with MIT License | 6 votes |
def load(self): try: s = Session.objects.get( session_key=self.session_key, expire_date__gt=timezone.now() ) self.user_id = s.user_id # do not overwrite user_agent/ip, as those might have been updated if self.user_agent != s.user_agent or self.ip != s.ip: self.modified = True return self.decode(s.session_data) except (Session.DoesNotExist, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(force_text(e)) self.create() return {}
Example #22
Source File: utils.py From swagger-django-generator with BSD 3-Clause "New" or "Revised" License | 6 votes |
def body_to_dict(body, schema): # type: (str, Dict) -> Dict """ :param body: The body content :param schema: The expected JSONSchema :return: A dictionary containing the parsed body :raises SuspiciousOperation: If the body is not in JSON format, or does not conform to the specified schema. """ try: data = json.loads(body) jsonschema.validate(data, schema=schema) return data except Exception as e: # The SuspiciousOperation exception will result in an # HttpResponseBadRequest response. raise SuspiciousOperation(e)
Example #23
Source File: utils.py From swagger-django-generator with BSD 3-Clause "New" or "Revised" License | 6 votes |
def body_to_dict(body, schema): # type: (str, Dict) -> Dict """ :param body: The body content :param schema: The expected JSONSchema :return: A dictionary containing the parsed body :raises SuspiciousOperation: If the body is not in JSON format, or does not conform to the specified schema. """ try: data = json.loads(body) jsonschema.validate(data, schema=schema) return data except Exception as e: # The SuspiciousOperation exception will result in an # HttpResponseBadRequest response. raise SuspiciousOperation(e)
Example #24
Source File: utils.py From swagger-django-generator with BSD 3-Clause "New" or "Revised" License | 6 votes |
def body_to_dict(body, schema): # type: (str, Dict) -> Dict """ :param body: The body content :param schema: The expected JSONSchema :return: A dictionary containing the parsed body :raises SuspiciousOperation: If the body is not in JSON format, or does not conform to the specified schema. """ try: data = json.loads(body) jsonschema.validate(data, schema=schema) return data except Exception as e: # The SuspiciousOperation exception will result in an # HttpResponseBadRequest response. raise SuspiciousOperation(e)
Example #25
Source File: test_auth.py From mozilla-django-oidc with Mozilla Public License 2.0 | 6 votes |
def test_disallowed_unsecured_invalid_token(self): """Test payload data from invalid secure token (unsecured disallowed).""" header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'})) payload = force_bytes(json.dumps({'foo': 'bar'})) # Compute signature key = b'mysupersecuretestkey' fake_key = b'mysupersecurefaketestkey' h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend()) msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload))) h.update(force_bytes(msg)) signature = b64encode(h.finalize()) token = '{}.{}.{}'.format( smart_text(b64encode(header)), smart_text(b64encode(payload)), smart_text(signature) ) token_bytes = force_bytes(token) key_text = smart_text(fake_key) with self.assertRaises(SuspiciousOperation) as ctx: self.backend.get_payload_data(token_bytes, key_text) self.assertEqual(ctx.exception.args[0], 'JWS token verification failed.')
Example #26
Source File: backends.py From django-qiniu-storage with MIT License | 6 votes |
def _normalize_name(self, name): """ Normalizes the name so that paths like /path/to/ignored/../foo.txt work. We check to make sure that the path pointed to is not outside the directory specified by the LOCATION setting. """ base_path = force_text(self.location) base_path = base_path.rstrip('/') final_path = urljoin(base_path.rstrip('/') + "/", name) base_path_len = len(base_path) if (not final_path.startswith(base_path) or final_path[base_path_len:base_path_len + 1] not in ('', '/')): raise SuspiciousOperation("Attempted access to '%s' denied." % name) return final_path.lstrip('/')
Example #27
Source File: api_views.py From zentral with Apache License 2.0 | 5 votes |
def post(self, request, *args, **kwargs): payload = request.body if not payload: data = payload else: content_encoding = request.META.get('HTTP_CONTENT_ENCODING', None) if content_encoding: # try to decompress the payload. if content_encoding == "deflate" \ or "santa" in self.user_agent and content_encoding == "zlib" \ or self.user_agent == "Zentral/mnkpf 0.1" and content_encoding == "gzip": payload = zlib.decompress(payload) elif content_encoding == "gzip": payload = GzipFile(fileobj=request).read() else: return HttpResponse("Unsupported Media Type", status=415) try: payload = payload.decode(self.payload_encoding) except UnicodeDecodeError: err_msg_tmpl = 'Could not decode payload with encoding %s' logger.error(err_msg_tmpl, self.payload_encoding, extra={'request': request}) raise SuspiciousOperation(err_msg_tmpl % self.payload_encoding) try: data = json.loads(payload) except ValueError: raise SuspiciousOperation("Payload is not valid json") try: self.check_data_secret(data) except APIAuthError as auth_err: logger.error("APIAuthError %s", auth_err, extra={'request': request}) return HttpResponseForbidden(str(auth_err)) response_data = self.do_post(data) return JsonResponse(response_data)
Example #28
Source File: api.py From zentral with Apache License 2.0 | 5 votes |
def get_enroll_secret(self, data): try: return data["enroll_secret"] except KeyError: raise SuspiciousOperation("Missing enroll_secret key in osquery enroll request")
Example #29
Source File: api_views.py From zentral with Apache License 2.0 | 5 votes |
def abort(self, reason, **event_payload): if reason: event_payload["reason"] = reason self.post_event("failure", **event_payload) raise SuspiciousOperation(reason)
Example #30
Source File: db.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def _get_session_from_db(self): try: return self.model.objects.get( session_key=self.session_key, expire_date__gt=timezone.now() ) except (self.model.DoesNotExist, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(str(e)) self._session_key = None