From 84d163117ce81771e1cff8a9591cf01a1ccbe0cd Mon Sep 17 00:00:00 2001 From: Pieter Lambrecht Date: Mon, 21 Mar 2022 11:47:31 +0100 Subject: [PATCH] Raise 400 validation error on bad clientip --- netbox/netbox/api/authentication.py | 10 ++++++++-- netbox/users/models.py | 4 ++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/netbox/netbox/api/authentication.py b/netbox/netbox/api/authentication.py index ee871a5e3..2f86a1da2 100644 --- a/netbox/netbox/api/authentication.py +++ b/netbox/netbox/api/authentication.py @@ -1,4 +1,5 @@ from django.conf import settings +from django.core.exceptions import ValidationError from rest_framework import authentication, exceptions from rest_framework.permissions import BasePermission, DjangoObjectPermissions, SAFE_METHODS @@ -21,13 +22,18 @@ class TokenAuthentication(authentication.TokenAuthentication): # Replace 'HTTP_X_REAL_IP' with the settings variable choosen in #8867 if 'HTTP_X_REAL_IP' in request.META: clientip = request.META['HTTP_X_REAL_IP'].split(",")[0].strip() + http_header = 'HTTP_X_REAL_IP' elif 'REMOTE_ADDR' in request.META: clientip = request.META['REMOTE_ADDR'] + http_header = 'REMOTE_ADDR' else: raise exceptions.AuthenticationFailed(f"A HTTP header containing the SourceIP (HTTP_X_REAL_IP, REMOTE_ADDR) is missing from the request.") - if not token.validate_client_ip(clientip): - raise exceptions.AuthenticationFailed(f"Source IP {clientip} is not allowed to use this token.") + try: + if not token.validate_client_ip(clientip): + raise exceptions.AuthenticationFailed(f"Source IP {clientip} is not allowed to use this token.") + except ValidationError as ValidationErrorInfo: + raise exceptions.ValidationError(f"The value in the HTTP Header {http_header} has a ValidationError: {ValidationErrorInfo.message}") return authenticationresult diff --git a/netbox/users/models.py b/netbox/users/models.py index 86a891266..5ebb7621c 100644 --- a/netbox/users/models.py +++ b/netbox/users/models.py @@ -246,8 +246,8 @@ class Token(BigIDModel): try: ip_address = ipaddress.ip_address(raw_ip_address) - except ValueError: - raise ValidationError(f"{raw_ip_address} is an invalid IP address") + except ValueError as e: + raise ValidationError(str(e)) for ip_network in self.allowed_ips: if ip_address in ipaddress.ip_network(ip_network):