예제 #1
0
 def test_cleanes_with_v4_mapping(self):
     self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a'),
                      u'::ffff:10.10.10.10')
     self.assertEqual(clean_ipv6_address('::ffff:1234:1234'),
                      u'::ffff:18.52.18.52')
     self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52'),
                      u'::ffff:18.52.18.52')
예제 #2
0
 def test_cleans_plain_address(self):
     self.assertEqual(clean_ipv6_address("DEAD::0:BEEF"), "dead::beef")
     self.assertEqual(
         clean_ipv6_address("2001:000:a:0000:0:fe:fe:beef"), "2001:0:a::fe:fe:beef"
     )
     self.assertEqual(
         clean_ipv6_address("2001::a:0000:0:fe:fe:beef"), "2001:0:a::fe:fe:beef"
     )
예제 #3
0
 def test_unpacks_ipv4(self):
     self.assertEqual(
         clean_ipv6_address('::ffff:0a0a:0a0a', unpack_ipv4=True),
         u'10.10.10.10')
     self.assertEqual(
         clean_ipv6_address('::ffff:1234:1234', unpack_ipv4=True),
         u'18.52.18.52')
     self.assertEqual(
         clean_ipv6_address('::ffff:18.52.18.52', unpack_ipv4=True),
         u'18.52.18.52')
예제 #4
0
 def test_unpacks_ipv4(self):
     self.assertEqual(
         clean_ipv6_address("::ffff:0a0a:0a0a", unpack_ipv4=True), "10.10.10.10"
     )
     self.assertEqual(
         clean_ipv6_address("::ffff:1234:1234", unpack_ipv4=True), "18.52.18.52"
     )
     self.assertEqual(
         clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52"
     )
예제 #5
0
 def to_python(self, value):
     if value in validators.EMPTY_VALUES:
         return u''
     if value and ':' in value:
         return clean_ipv6_address(value, self.unpack_ipv4,
                                   self.error_messages['invalid'])
     return value
예제 #6
0
파일: fields.py 프로젝트: klinskih/django
 def to_python(self, value):
     if value in validators.EMPTY_VALUES:
         return ''
     if value and ':' in value:
             return clean_ipv6_address(value,
                 self.unpack_ipv4, self.error_messages['invalid'])
     return value
예제 #7
0
 def to_python(self, value):
     if value in self.empty_values:
         return ''
     value = value.strip()
     if value and ':' in value:
         return clean_ipv6_address(value, self.unpack_ipv4)
     return value
예제 #8
0
 def get_prep_value(self, value):
     if value and ':' in value:
         try:
             return clean_ipv6_address(value, self.unpack_ipv4)
         except exceptions.ValidationError:
             pass
     return value
예제 #9
0
파일: fields.py 프로젝트: mitsuhiko/django
 def to_python(self, value):
     if not value:
         return ''
     if value and ':' in value:
             return clean_ipv6_address(value,
                 self.unpack_ipv4, self.error_messages['invalid'])
     return value
예제 #10
0
 def to_python(self, value):
     if value in self.empty_values:
         return ''
     value = value.strip()
     if value and ':' in value:
         return clean_ipv6_address(value, self.unpack_ipv4)
     return value
예제 #11
0
def validate_and_normalize_ip(ip_address, ip_type):
    """
    Validate and normalize the given IP address

    :param ip_address: the IP address to validate and normalize
    :type ip_address: str
    :param ip_type: the type of the IP address
    :type ip_type: str
    :returns: tuple: (Valid normalized IP, Error message)
    """

    cleaned = None
    if ip_type in (IPTypes.IPV4_SUBNET, IPTypes.IPV6_SUBNET):
        try:
            if '/' not in ip_address:
                raise ValidationError("")
            cidr_parts = ip_address.split('/')
            if int(cidr_parts[1]) < 0 or int(cidr_parts[1]) > 128:
                raise ValidationError("")
            if ':' not in cidr_parts[0] and int(cidr_parts[1]) > 32:
                raise ValidationError("")
            ip_address = cidr_parts[0]
        except (ValidationError, ValueError):
            return ("", "Invalid CIDR address")

    if ip_type in (IPTypes.IPV4_ADDRESS, IPTypes.IPV4_SUBNET):
        try:
            validate_ipv4_address(ip_address)

            # Remove leading zeros
            cleaned = []
            for octet in ip_address.split('.'):
                cleaned.append(octet.lstrip('0') or '0')
            cleaned = '.'.join(cleaned)
        except ValidationError:
            if ip_type == IPTypes.IPV4_ADDRESS:
                return ("", "Invalid IPv4 address")
            else:
                return ("", "Invalid IPv4 CIDR address")

    if ip_type in (IPTypes.IPV6_ADDRESS, IPTypes.IPV6_SUBNET):
        try:
            validate_ipv6_address(ip_address)

            # Replaces the longest continuous zero-sequence with "::" and
            # removes leading zeroes and makes sure all hextets are lowercase.
            cleaned = clean_ipv6_address(ip_address)
        except ValidationError:
            if ip_type == IPTypes.IPV6_ADDRESS:
                return ("", "Invalid IPv6 address")
            else:
                return ("", "Invalid IPv6 CIDR address")

    if not cleaned:
        return ("", "Invalid IP type.")
    elif ip_type in (IPTypes.IPV4_SUBNET, IPTypes.IPV6_SUBNET):
        return (cleaned + '/' + cidr_parts[1], "")
    else:
        return (cleaned, "")
예제 #12
0
def validate_and_normalize_ip(ip_address, ip_type):
    """
    Validate and normalize the given IP address

    :param ip_address: the IP address to validate and normalize
    :type ip_address: str
    :param ip_type: the type of the IP address
    :type ip_type: str
    :returns: tuple: (Valid normalized IP, Error message)
    """

    cleaned = None
    if "cidr" in ip_type:
        try:
            if "/" not in ip_address:
                raise ValidationError("")
            cidr_parts = ip_address.split("/")
            if int(cidr_parts[1]) < 0 or int(cidr_parts[1]) > 128:
                raise ValidationError("")
            if ":" not in cidr_parts[0] and int(cidr_parts[1]) > 32:
                raise ValidationError("")
            ip_address = cidr_parts[0]
        except (ValidationError, ValueError):
            return ("", "Invalid CIDR address")

    if "Address - ipv4" in ip_type or "cidr" in ip_type:
        try:
            validate_ipv4_address(ip_address)

            # Remove leading zeros
            cleaned = []
            for octet in ip_address.split("."):
                cleaned.append(octet.lstrip("0") or "0")
            cleaned = ".".join(cleaned)
        except ValidationError:
            if "cidr" not in ip_type:
                return ("", "Invalid IPv4 address")
            else:
                ip_type = "cidr_ipv6"

    if "Address - ipv6" in ip_type or ip_type == "cidr_ipv6":
        try:
            validate_ipv6_address(ip_address)

            # Replaces the longest continuous zero-sequence with "::" and
            # removes leading zeroes and makes sure all hextets are lowercase.
            cleaned = clean_ipv6_address(ip_address)
        except ValidationError:
            if "cidr" in ip_type:
                return ("", "Invalid CIDR address")
            else:
                return ("", "Invalid IPv6 address")

    if not cleaned:
        return ("", "Invalid IP type.")
    elif "cidr" in ip_type:
        return (cleaned + "/" + cidr_parts[1], "")
    else:
        return (cleaned, "")
예제 #13
0
파일: handlers.py 프로젝트: brlogan/crits
def validate_and_normalize_ip(ip_address, ip_type):
    """
    Validate and normalize the given IP address

    :param ip_address: the IP address to validate and normalize
    :type ip_address: str
    :param ip_type: the type of the IP address
    :type ip_type: str
    :returns: tuple: (Valid normalized IP, Error message)
    """

    cleaned = None
    if ip_type in (IPTypes.IPV4_SUBNET, IPTypes.IPV6_SUBNET):
        try:
            if '/' not in ip_address:
                raise ValidationError("")
            cidr_parts = ip_address.split('/')
            if int(cidr_parts[1]) < 0 or int(cidr_parts[1]) > 128:
                raise ValidationError("")
            if ':' not in cidr_parts[0] and int(cidr_parts[1]) > 32:
                raise ValidationError("")
            ip_address = cidr_parts[0]
        except (ValidationError, ValueError):
            return ("", "Invalid CIDR address")

    if ip_type in (IPTypes.IPV4_ADDRESS, IPTypes.IPV4_SUBNET):
        try:
            validate_ipv4_address(ip_address)

            # Remove leading zeros
            cleaned = []
            for octet in ip_address.split('.'):
                cleaned.append(octet.lstrip('0') or '0')
            cleaned = '.'.join(cleaned)
        except ValidationError:
            if ip_type == IPTypes.IPV4_ADDRESS:
                return ("", "Invalid IPv4 address")
            else:
                return ("", "Invalid IPv4 CIDR address")

    if ip_type in (IPTypes.IPV6_ADDRESS, IPTypes.IPV6_SUBNET):
        try:
            validate_ipv6_address(ip_address)

            # Replaces the longest continuous zero-sequence with "::" and
            # removes leading zeroes and makes sure all hextets are lowercase.
            cleaned = clean_ipv6_address(ip_address)
        except ValidationError:
            if ip_type == IPTypes.IPV6_ADDRESS:
                return ("", "Invalid IPv6 address")
            else:
                return ("", "Invalid IPv6 CIDR address")

    if not cleaned:
        return ("", "Invalid IP type.")
    elif ip_type in (IPTypes.IPV4_SUBNET, IPTypes.IPV6_SUBNET):
        return (cleaned + '/' + cidr_parts[1], "")
    else:
        return (cleaned, "")
예제 #14
0
 def get_prep_value(self, value):
     if value is None:
         return value
     if value and ":" in value:
         try:
             return clean_ipv6_address(value, self.unpack_ipv4)
         except exceptions.ValidationError:
             pass
     return six.text_type(value)
예제 #15
0
파일: models.py 프로젝트: lowks/dj-oydiv
 def is_ip_allowed(self, ip):
     if not self.use_ip_auth:
         return True
     try:
         validators.validate_ipv46_address(ip)
     except ValidationError:
         return False
     if ipv6.is_valid_ipv6_address(ip):
         ip = ipv6.clean_ipv6_address(ip)
     return self._allowed_cleaned_ip(ip)
예제 #16
0
파일: fields.py 프로젝트: Relrin/aiorest-ws
    def to_internal_value(self, data):
        if not isinstance(data, six.string_types):
            self.raise_error('invalid', value=data)

        if ':' in data:
            try:
                if self.protocol in ('both', 'ipv6'):
                    return clean_ipv6_address(data, self.unpack_ipv4)
            except DjangoValidationError:
                self.raise_error('invalid', value=data)

        return super(IPAddressField, self).to_internal_value(data)
예제 #17
0
    def to_internal_value(self, data):
        """Validate the value coming in to be saved on the instance.
        """
        if not isinstance(data, str):
            self.fail('invalid', value=data)

        if ':' in data:
            try:
                if self.protocol in ('both', 'ipv6'):
                    return clean_ipv6_address(data, self.unpack_ipv4)
            except DjangoValidationError:
                self.fail('invalid', value=data)
        else:
            if not host_regex.match(data):
                self.fail('invalid', value=data)

        return super().to_internal_value(data)
예제 #18
0
def get_ip_address_from_request(request):
    """ Makes the best attempt to get the client's real IP or return the loopback """
    
    # Would rather rely on middleware to set up a good REMOTE_ADDR than try to get
    # fancy here. Also, just use django's built in ipv4/ipv6 normalization logic
    ip_address = request.META.get('REMOTE_ADDR', 'bad address')
    try:
        validate_ipv4_address(ip_address)
    except:
        try:
            validate_ipv6_address(ip_address)
            ip_address = clean_ipv6_address(ip_address, True)
        except:
            log.error("Could not parse address {0}".format(ip_address))
            ip_address = "127.0.0.1"
        
    return ip_address
예제 #19
0
 def to_python(self, value):
     if value:
         if ':' in value: # Maybe we are ipv6
             if '/' in value:
                 [addr,mask] = value.rsplit('/',1)
             else:
                 addr=value
                 mask='128'
             addr=clean_ipv6_address(addr,
                     self.unpack_ipv4, self.error_messages['invalid'])
         else:
             if '/' in value:
                 [addr,mask] = value.rsplit('/',1)
             else:
                 addr=value
                 mask='32'
         value="%s/%s"%(addr,mask)
     return value
예제 #20
0
 def to_python(self, value):
     if value in validators.EMPTY_VALUES:
         return ''
     if value:
         if ':' in value:
             if '/' in value:
                 [addr,mask] = value.rsplit('/', 1)
             else:
                 addr=value
                 mask='128'
             addr=clean_ipv6_address(addr,
                     self.unpack_ipv4, self.error_messages['invalid'])
         else:
             if '/' in value:
                 [addr,mask] = value.rsplit('/',1)
             else:
                 addr=value
                 mask='32'
         value="%s/%s"%(addr,mask)
     return value
예제 #21
0
 def get_prep_value(self, value):
     if value and type(value) == type("str"):
         if ':' in value: # Maybe we are ipv6
             if '/' in value:
                 [addr,mask] = value.rsplit('/',1)
             else:
                 addr=value
                 mask='128'
             try:
                 addr=clean_ipv6_address(addr,
                     self.unpack_ipv4, self.error_messages['invalid'])
             except ValidationError:
                 pass
         else:
             if '/' in value:
                 [addr,mask] = value.rsplit('/',1)
             else:
                 addr=value
                 mask='32'
         value="%s/%s"%(addr,mask)
     return value
예제 #22
0
 def to_python(self, value):
     if value and ':' in value:
         return clean_ipv6_address(value,
             self.unpack_ipv4, self.error_messages['invalid'])
     return value
예제 #23
0
파일: models.py 프로젝트: lowks/dj-oydiv
 def save(self, *args, **kwargs):
     validators.validate_ipv46_address(self.ip)
     if ipv6.is_valid_ipv6_address(self.ip):
         self.ip = ipv6.clean_ipv6_address(self.ip)
     super(IPModel, self).save(*args, **kwargs)
예제 #24
0
 def to_python(self, value):
     if value and ":" in value:
         return clean_ipv6_address(value, self.unpack_ipv4, self.error_messages["invalid"])
     return value
예제 #25
0
 def test_unpacks_ipv4(self):
     self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a', unpack_ipv4=True), '10.10.10.10')
     self.assertEqual(clean_ipv6_address('::ffff:1234:1234', unpack_ipv4=True), '18.52.18.52')
     self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52', unpack_ipv4=True), '18.52.18.52')
예제 #26
0
 def test_cleanes_with_v4_mapping(self):
     self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a'), '::ffff:10.10.10.10')
     self.assertEqual(clean_ipv6_address('::ffff:1234:1234'), '::ffff:18.52.18.52')
     self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52'), '::ffff:18.52.18.52')
     self.assertEqual(clean_ipv6_address('::ffff:0.52.18.52'), '::ffff:0.52.18.52')
     self.assertEqual(clean_ipv6_address('::ffff:0.0.0.0'), '::ffff:0.0.0.0')
예제 #27
0
 def test_cleanes_plain_address(self):
     self.assertEqual(clean_ipv6_address('DEAD::0:BEEF'), 'dead::beef')
     self.assertEqual(clean_ipv6_address('2001:000:a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef')
     self.assertEqual(clean_ipv6_address('2001::a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef')
예제 #28
0
 def test_cleans_with_v4_mapping(self):
     self.assertEqual(clean_ipv6_address("::ffff:0a0a:0a0a"), "::ffff:10.10.10.10")
     self.assertEqual(clean_ipv6_address("::ffff:1234:1234"), "::ffff:18.52.18.52")
     self.assertEqual(clean_ipv6_address("::ffff:18.52.18.52"), "::ffff:18.52.18.52")
     self.assertEqual(clean_ipv6_address("::ffff:0.52.18.52"), "::ffff:0.52.18.52")
     self.assertEqual(clean_ipv6_address("::ffff:0.0.0.0"), "::ffff:0.0.0.0")
예제 #29
0
파일: fields.py 프로젝트: tovenja/django
 def to_python(self, value):
     if value in validators.EMPTY_VALUES:
         return u""
     if value and ":" in value:
         return clean_ipv6_address(value, self.unpack_ipv4, self.error_messages["invalid"])
     return value
예제 #30
0
 def test_cleanes_plain_address(self):
     self.assertEqual(clean_ipv6_address('DEAD::0:BEEF'), u'dead::beef')
     self.assertEqual(clean_ipv6_address('2001:000:a:0000:0:fe:fe:beef'),
                      u'2001:0:a::fe:fe:beef')
     self.assertEqual(clean_ipv6_address('2001::a:0000:0:fe:fe:beef'),
                      u'2001:0:a::fe:fe:beef')
예제 #31
0
def test_clean_ipv6_address(inp):
    try:
        clean_ipv6_address(inp)
    except ValidationError:
        pass
예제 #32
0
"""