Ejemplo n.º 1
0
    def get(self, request):
        try:
            input1 = request.GET.get("input1")
            input2 = request.GET.get("input2")

            validate_ipv4_address(input1)
            validate_ipv4_address(input2)

            first = ipaddress.IPv4Address(input1)
            last = ipaddress.IPv4Address(input2)
            queryset = Router.objects.filter(is_active=True)
            summary = " ".join(map(str, ipaddress.summarize_address_range(first, last)))

            final_data = []
            for i in queryset:
                if ipaddress.IPv4Network(i.loopback).__str__() in summary:
                    final_data.append(i)

            data = RouterSerializer(final_data, many=True)
            return Response({"data": data.data, "success": True}, status=200)
        except ValueError as error:
            traceback.print_exc()
            return Response({"error": error, "success": False}, status=400)
        except ValidationError as error:
            traceback.print_exc()
            return Response({"error": error, "success": False}, status=400)
        except Exception as error:
            traceback.print_exc()
            return Response({"error": str(error), "success": False}, status=400)
Ejemplo n.º 2
0
def create_or_view_network_tool(request):


    if request.method  == "POST":
    
        rtype = request.POST['type']
        ip = request.POST['ip']
        is_url = False

        try:
            try:
                validators.validate_ipv4_address(ip) # ip format x.x.x.x
            except ValidationError, error: # url format www.xxx.xxx
                value = ip
                if not '://' in value:
                    value = 'https://%s' % value
                urlvalidator = validators.URLValidator()
                urlvalidator(value)
                is_url  = True

            if rtype == "ping":
                rcode, output = networkutils.ping(ip)
            elif rtype == "traceroute":
                rcode, output = networkutils.traceroute(ip)
            elif rtype == "nslookup":
                try:
                    if is_url:
                        output = networkutils.resolve_name(ip)
                    else:
                        output = networkutils.resolve_addr(ip)
                except (networkutils.HostAddrNotFound,
                         networkutils.HostNameNotFound), error:
                    output = "Não encontrado"
Ejemplo n.º 3
0
    def to_python(self, value):
        if not value:
            return None

        if isinstance(value, IPAddress):
            return value

        # netaddr is a bit too liberal with what it accepts as a valid IP address. For example, '1.2.3' will become
        # IPAddress('1.2.0.3'). Here, we employ Django's built-in IPv4 and IPv6 address validators as a sanity check.
        try:
            validate_ipv4_address(value)
        except ValidationError:
            try:
                validate_ipv6_address(value)
            except ValidationError:
                raise ValidationError(
                    "Invalid IPv4/IPv6 address format: {}".format(value))

        try:
            return IPAddress(value)
        except ValueError:
            raise ValidationError(
                'This field requires an IP address without a mask.')
        except AddrFormatError:
            raise ValidationError(
                "Please specify a valid IPv4 or IPv6 address.")
Ejemplo n.º 4
0
def validate_ipv4_range(value):
    try: 
        ip, offset = value.split('#')
        validate_ipv4_address(ip)
        int(offset)
    except:
        raise ValidationError('Range %s has not a valid format (IPv4#N).' % value)
Ejemplo n.º 5
0
def update(request, id):
    router = Router.objects.get(pk=id)

    if request.method == 'POST':
        sapid = request.POST['sapid']
        host = request.POST['host']
        loop = request.POST['loop']
        mac = request.POST['mac']

        try:
            validate_ipv4_address(loop)
            # Success
        except ValidationError:
            data = {'message': 'Invalid Loopback !!!'}
            return HttpResponse(
                json.dumps(data), content_type='application/json')

        if not is_valid_macaddr802(mac):
            data = {'message': 'Invalid Mac Address !!!'}
            return HttpResponse(
                json.dumps(data), content_type='application/json')

        router.sapId = sapid
        router.hostname = host
        router.loopback = loop
        router.macAddress = mac
        router.save()
        data = {'message': 'Success'}
        return HttpResponse(
            json.dumps(data), content_type='application/json')

    context = {
        'router': router
    }
    return render(request, 'update.html', context)
Ejemplo n.º 6
0
def create(request):
    if request.method == 'POST':
        sapid = request.POST['sapid']
        host = request.POST['host']
        loop = request.POST['loop']
        mac = request.POST['mac']

        try:
            validate_ipv4_address(loop)
            # Success
        except ValidationError:
            data = {'message': 'Invalid Loopback !!!'}
            return HttpResponse(
                json.dumps(data), content_type='application/json')

        if not is_valid_macaddr802(mac):
            data = {'message': 'Invalid Mac Address !!!'}
            return HttpResponse(
                json.dumps(data), content_type='application/json')

        route = Router.objects.create(
            sapId=sapid,
            hostname=host,
            loopback=loop,
            macAddress=mac)
        route.save()
        data = {'message': 'Success'}
        return HttpResponse(
            json.dumps(data), content_type='application/json')

    return render(request, 'create.html')
Ejemplo n.º 7
0
def validate_ip_bool(address):
    try:

        validate_ipv4_address(address)
        return True
    except ValidationError:
        return False
Ejemplo n.º 8
0
def ip_or_none(ip):
    """Return IP address if it is valide, None otherwise"""
    try:
        validate_ipv4_address(ip)
        return ip
    except ValidationError:
        return None
Ejemplo n.º 9
0
def get_ip(request):
    """
    Retrieves the remote IP address from the request data.  If the user is
    behind a proxy, they may have a comma-separated list of IP addresses, so
    we need to account for that.  In such a case, only the first IP in the
    list will be retrieved.  Also, some hosts that use a proxy will put the
    REMOTE_ADDR into HTTP_X_FORWARDED_FOR.  This will handle pulling back the
    IP from the proper place.

    **NOTE** This function was taken from django-tracking (MIT LICENSE)
             http://code.google.com/p/django-tracking/
    """

    # if neither header contain a value, just use local loopback
    ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META.get("REMOTE_ADDR", "127.0.0.1"))
    if ip_address:
        # make sure we have one and only one IP
        try:
            validate_ipv4_address(ip_address)
        except ValidationError:
            try:
                validate_ipv6_address(ip_address)
            except ValidationError:
                ip_address = "10.0.0.1"
    else:
        ip_address = "10.0.0.1"

    return ip_address
Ejemplo n.º 10
0
    def validate(self):
        if not isinstance(self.config, dict):
            logger.error('unexcepted config format')
            raise TypeError('configuration type error. expected dict, got {err_}'.format(err_=type(self.config)))

        for field in self.fields:
            valid = True
            value = self.config['server']['conf'][field[0]]
            if value:
                if field[0] == 'server_ip' and value not in self.domain_whitelist:
                    try:
                        validate_ipv4_address(value)
                    except ValidationError:
                        valid = False
                elif field[0] == 'server_domain' and value not in self.domain_whitelist:
                    url_validator = URLValidator()
                    try:
                        url_validator(value)
                    except ValidationError:
                        valid = False
                elif (field[0] == 'server_type' and value not in self.server_types) or (
                        field[0] == 'emu_type' and value not in self.emu_types):
                    valid = False
                else:
                    if not isinstance(value, field[1]) or (field[2] > 0 and len(value) < field[2]):
                        valid = False

                if not valid:
                    self.config['server']['conf'][field[0]] = field[3]
                    logger.warn(self.message.format(field=field[0], default=field[3]))
                    self.errors.append(self.message.format(field=field[0], default=field[3]))
Ejemplo n.º 11
0
    def clean(self):
        cleaned_data = super(OpenVASForm, self).clean()
        urls = cleaned_data.get("urls")
        ips = cleaned_data.get("ips")
        config = cleaned_data.get("config")
        print(ips)
        if (config == "Full and fast ultimate"
                or config == "Full and very deep ultimate") and (
                    not can_ultimate(self.user)):
            raise forms.ValidationError(
                _("You are not allowed to scan in Ultimate mode, please contact your administrator if you need this permission. "
                  ))

        if urls == "" and ips == "":
            raise forms.ValidationError(
                _("Please specify at least 1 target, by URL, by IP or both"))

        if (ips is not None):
            ip = ips.replace(" ", "").split(",")
            for i in ip:
                if i != "":
                    try:
                        validate_ipv4_address(i)
                    except:
                        if not can_network(self.user):
                            raise ValidationError(
                                _((my_default_errors_IP['network'])))
Ejemplo n.º 12
0
def create_or_view_network_tool(request):

    if request.method == "POST":

        rtype = request.POST['type']
        ip = request.POST['ip']
        is_url = False

        try:
            try:
                validators.validate_ipv4_address(ip)  # ip format x.x.x.x
            except ValidationError, error:  # url format www.xxx.xxx
                value = ip
                if not '://' in value:
                    value = 'https://%s' % value
                urlvalidator = validators.URLValidator()
                urlvalidator(value)
                is_url = True

            if rtype == "ping":
                rcode, output = networkutils.ping(ip)
            elif rtype == "traceroute":
                rcode, output = networkutils.traceroute(ip)
            elif rtype == "nslookup":
                try:
                    if is_url:
                        output = networkutils.resolve_name(ip)
                    else:
                        output = networkutils.resolve_addr(ip)
                except (networkutils.HostAddrNotFound,
                        networkutils.HostNameNotFound), error:
                    output = "Não encontrado"
Ejemplo n.º 13
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, "")
Ejemplo n.º 14
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, "")
Ejemplo n.º 15
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, "")
Ejemplo n.º 16
0
def ip_validator(ip):
    try:
        validate_ipv4_address(ip)
    except ValidationError:
        try:
            validate_ipv6_address(ip)
        except ValidationError:
            raise ValidationError('Invalid IP address')
Ejemplo n.º 17
0
 def clean_controller_ip(self):
     controller_ip = None
     if "controller_ip" in self.cleaned_data:
         controller_ip = self.cleaned_data["controller_ip"]
     # Optional field. May not be there
     if controller_ip:
         validators.validate_ipv4_address(controller_ip)
     return controller_ip
Ejemplo n.º 18
0
 def clean_controller_ip(self):
     controller_ip = None
     if "controller_ip" in self.cleaned_data:
         controller_ip = self.cleaned_data["controller_ip"]
     # Optional field. May not be there
     if controller_ip:
         validators.validate_ipv4_address(controller_ip)
     return controller_ip
Ejemplo n.º 19
0
    def validate(self, value):
        "Check if value consists only of valid ipaddress."

        # Use the parent's handling of required fields, etc.
        super(MultiIpaddressField, self).validate(value)

        for ip in value:
            validate_ipv4_address(ip)
Ejemplo n.º 20
0
 def perform_checking(ip):
     django_validator.validate_ipv4_address(ip)
     if not self.existing_subnet:
         raise forms.ValidationError(_("Cannot get allowed subnet for the environment, " "consult your admin"))
     elif not netaddr.IPAddress(ip) in netaddr.IPNetwork(self.existing_subnet):
         raise forms.ValidationError(
             _("Specified IP address should belong to {0} " "subnet").format(self.existing_subnet)
         )
Ejemplo n.º 21
0
def validate_ipv4_range(value):
    try:
        ip, offset = value.split('#')
        validate_ipv4_address(ip)
        int(offset)
    except:
        raise ValidationError('Range %s has not a valid format (IPv4#N).' %
                              value)
Ejemplo n.º 22
0
 def clean_content(self):
     """Clean content based on selected type"""
     data = self.cleaned_data.get('content')
     _type = self.cleaned_data.get('type')
     if _type == 'A':
         validate_ipv4_address(data)
     elif _type == 'AAAA':
         validate_ipv6_address(data)
     return data
Ejemplo n.º 23
0
def validate_freeswitch_ipaddress(value):
    try:
        validate_ipv4_address(value)
    except ValidationError, e:
        try:
            validate_freeswitch_variable(value)
        except ValidationError:
            raise ValidationError(_(u'Enter a valid IPv4 address, '
                'or a FreeSWITCH variable.'))
Ejemplo n.º 24
0
def should_give_doge(request, send_addr=None):
  ip = get_ip(request)
  validate_ipv4_address(ip)
  week_ago = datetime.utcnow().replace(tzinfo=utc) - timedelta(days=7)
  query = Q(ip_address=ip)
  if send_addr:
    query = query | Q(sent_address=send_addr)
  transactions = Transaction.objects.filter(query).filter(tx_time__gt=week_ago)
  return len(transactions) == 0
Ejemplo n.º 25
0
 def clean_content(self):
     """Ensures that content is an IPv4 address."""
     content = self.cleaned_data.get('content')
     try:
         validate_ipv4_address(content)
     except ValidationError:
         raise forms.ValidationError("""Content should contain an IPv4 address""")
     else:
         return content
Ejemplo n.º 26
0
    def get_object(self):
        ip_address = self.request.query_params.get('ip', None)
        try:
            validate_ipv4_address(ip_address)
        except ValidationError:
            raise Http404()
        obj = get_object_or_404(GeoLocationData, ip=ip_address)

        return obj
Ejemplo n.º 27
0
def validate_hostname(val):
    try:
        validate_ipv4_address(val)
    except ValidationError:
        # ip may in fact be a hostname
        # http://www.regextester.com/23
        HOSTNAME_RX = r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$'
        if not re.match(HOSTNAME_RX, val):
            raise ValidationError('Invalid hostname or IP')
Ejemplo n.º 28
0
 def clean_content(self):
     """Ensures that content is an IPv4 address."""
     content = self.cleaned_data.get('content')
     try:
         validate_ipv4_address(content)
     except ValidationError:
         raise forms.ValidationError("""Content should contain an IPv4 address""")
     else:
         return content
Ejemplo n.º 29
0
 def clean_value(self, value, operator_slug, request):
     if value is None:
         return value
     elif operator_slug not in {OPERATORS.CONTAINS, OPERATORS.EXACT, OPERATORS.STARTSWITH, OPERATORS.ENDSWITH}:
         try:
             validate_ipv4_address(value)
         except ValidationError:
             raise FilterValueError(ugettext('Value must be in format IPv4.'))
     return value
Ejemplo n.º 30
0
def getClientAdress( request ):
    
    ip = request.get_host()
    
    try:
        validate_ipv4_address( ip )
    except ValidationError:
        ip = ''
    
    return ip
Ejemplo n.º 31
0
 def inner(value):
     try:
         validate_ipv4_address(value)
     except ValidationError:
         try:
             validate_ipv6_address(value)
         except ValidationError:
             raise argparse.ArgumentTypeError(
                 'Enter a valid IPv4 or IPv6 address')
     return value
Ejemplo n.º 32
0
 def process_request(self, request):
     if request.user.is_authenticated():
         ip = request.META.get('REMOTE_ADDR', '')
         try:
             validate_ipv4_address(ip)
             if request.user.last_ip != ip:
                 request.user.last_ip = ip
                 request.user.save()
         except ValidationError:
             pass
Ejemplo n.º 33
0
 def clean_content_field(self):
     """Perform a type-dependent validation of content field"""
     if self.type == "A":
         validate_ipv4_address(self.content)
     elif self.type == "AAAA":
         validate_ipv6_address(self.content)
     elif self.type == "SOA":
         validate_soa(self.content)
     elif self.type in DOMAIN_NAME_RECORDS:
         validate_domain_name(self.content)
Ejemplo n.º 34
0
 def perform_checking(ip):
     validate_ipv4_address(ip)
     if not self.existing_subnet:
         raise forms.ValidationError(
             _('Cannot get allowed subnet for the environment, '
               'consult your admin'))
     elif not IPAddress(ip) in IPNetwork(self.existing_subnet):
         raise forms.ValidationError(
             _('Specified IP address should belong to {0} '
               'subnet'.format(self.existing_subnet)))
Ejemplo n.º 35
0
 def clean_content_field(self):
     """Perform a type-dependent validation of content field"""
     if self.type == 'A':
         validate_ipv4_address(self.content)
     elif self.type == 'AAAA':
         validate_ipv6_address(self.content)
     elif self.type == 'SOA':
         validate_soa(self.content)
     elif self.type in DOMAIN_NAME_RECORDS:
         validate_domain_name(self.content)
Ejemplo n.º 36
0
 def process_request(self, request):
     if request.user.is_authenticated():
         ip = request.META.get('REMOTE_ADDR', '')
         try:
             validate_ipv4_address(ip)
             if request.user.last_ip != ip:
                 request.user.last_ip = ip
                 request.user.save()
         except ValidationError:
             pass
Ejemplo n.º 37
0
def getClientAdress(request):

    ip = request.get_host()

    try:
        validate_ipv4_address(ip)
    except ValidationError:
        ip = ''

    return ip
Ejemplo n.º 38
0
 def validate_ipv46_address(self, value):
     from django.core.validators import validate_ipv4_address, validate_ipv6_address
     try:
         validate_ipv4_address(value)
         return 'ipv4'
     except ValidationError:
         try:
             validate_ipv6_address(value)
             return 'ipv6'
         except ValidationError:
             raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
Ejemplo n.º 39
0
    def process_request(self, request):
        host = request.get_host()
        domain, port = split_domain_port(host)
        try:
            validate_ipv4_address(domain)
        except ValidationError:
            # not an IP address. Call the superclass
            return super(EnforceHostIPMiddleware, self).process_request(request)

        # it is an IP address
        return
Ejemplo n.º 40
0
    def process_request(self, request):
        host = request.get_host()
        domain, port = split_domain_port(host)
        try:
            validate_ipv4_address(domain)
        except ValidationError:
            # not an IP address. Call the superclass
            return super(EnforceHostIPMiddleware, self).process_request(request)

        # it is an IP address
        return
Ejemplo n.º 41
0
 def validate_ip(value):
     try:
         validate_ipv4_address(value)
     except:
         raise ValidationError(_(my_default_errors_IP['invalid']))
     else:
         b = False
         for d in valid_domains:
             if value in IPNetwork(d):
                 b = True
         if not b:
             raise ValidationError(_(my_default_errors_IP['domain']))
Ejemplo n.º 42
0
 def validate_ipv46_address(self, value):
     from django.core.validators import validate_ipv4_address, validate_ipv6_address
     try:
         validate_ipv4_address(value)
         return 'ipv4'
     except ValidationError:
         try:
             validate_ipv6_address(value)
             return 'ipv6'
         except ValidationError:
             raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'),
                                   code='invalid')
Ejemplo n.º 43
0
 def clean_value(self, value, operator_slug, request):
     if value is None:
         return value
     elif operator_slug not in {
             OPERATORS.CONTAINS, OPERATORS.EXACT, OPERATORS.STARTSWITH,
             OPERATORS.ENDSWITH
     }:
         try:
             validate_ipv4_address(value)
         except ValidationError:
             raise FilterValueError(
                 ugettext('Value must be in format IPv4.'))
     return value
    def test_filling_IPAddressField(self):
        obj = baker.make(models.DummyGenericIPAddressFieldModel)
        field = models.DummyGenericIPAddressFieldModel._meta.get_field('ipv4_field')
        assert isinstance(field, fields.GenericIPAddressField)
        assert isinstance(obj.ipv4_field, str)

        validate_ipv4_address(obj.ipv4_field)

        if hasattr(obj, 'ipv6_field'):
            assert isinstance(obj.ipv6_field, str)
            assert isinstance(obj.ipv46_field, str)

            validate_ipv6_address(obj.ipv6_field)
            validate_ipv46_address(obj.ipv46_field)
Ejemplo n.º 45
0
def modify_client(request, client_id):
    user_client = request.user.my_userprofile.client
    if not user_client:
        raise Exception(u"Pas de client dans le profil pour l'utilisateur %s." % request.user)

    client = get_object_or_404(Client, pk=client_id)
    if not user_has_perms_on_client(request.user, client):
        raise PermissionDenied

    coordinate = client.coordinates or Coordinate()
    if request.method == "POST":
        client_form = ClientForm(request.POST, instance=client)
        coordinate_form = CoordinateForm(request.POST, instance=coordinate)
        if coordinate_form.is_valid() and client_form.is_valid():
            inst = coordinate_form.save()
            client.coordinates = inst
            client_form.save()
            #return redirect(reverse("common.views.modify_client"))
    else:
        client_form = ClientForm(instance=client)
        coordinate_form = CoordinateForm(instance=coordinate)

    # list hosts current client can see
    host_list = HostChar.objects.filter(client=client_id)
    ip_table = []
    for host in host_list:
        host_ip = host.host.ip.split()
        for ip in host_ip:
            try:
                validators.validate_ipv4_address(ip)
                ip_table.append([host.id,
                                 host.host,
                                 ip,
                                 host.host.type,
                                 host.host.id,
                                 host.name])
            except ValidationError:
                pass
    host_list_configure = ip_table
    host_list_qs = Host.objects.filter_by_user(request.user)
    host_list_qs = host_list_qs.filter(site__in=Client.objects.get_childs('parent', client.id))

    return render_to_response("common/client/modify.html", {
        "client": client,
        "client_form": client_form,
        "coordinate_form": coordinate_form,
        "host_list_qs": host_list_qs,
        "host_list_configure": host_list_configure,
    }, context_instance=RequestContext(request))
Ejemplo n.º 46
0
 def clean(self):
   cleaned_data = super(EditRecordForm, self).clean()
   name = cleaned_data.get('name')
   domain = Domain.objects.get(id=cleaned_data.get('domain'))
   type = cleaned_data.get('type')
   content = cleaned_data.get('content')
   mac = cleaned_data.get('mac')
   #fix a bug where validate_ipv6_address cannot process NoneType
   #So instead of passing None we pass 1 witch is invalid as well
   if content == None:
     content = '1'
   if type == 'A' or type == 'AAAA':
     ip_valid = True
   else:
     ip_valid = False
   if type == 'A':
     try: 
       validate_ipv4_address(content)
     except ValidationError:
       self.errors['content'] = self.error_class(['Not an IPv4 address'])
       ip_valid = False
     except AddrFormatError:
       self.errors['content'] = self.error_class(['Not an IPv4 address'])
       ip_valid = False
   if type == 'AAAA' and ip_valid:
     try: 
       validate_ipv6_address(content)
     except ValidationError:
       self.errors['content'] = self.error_class(['Not an IPv6 address'])
       ip_valid = False
   ranges = Range.objects.all()
   found = False
   if ip_valid:
     for range in ranges:
       if IPAddress(content) >= IPNetwork(range.cidr).network and IPAddress(content) <= IPNetwork(range.cidr).broadcast:
         found = True
         break
   if mac:
     if not re.match("[0-9a-f]{2}([\.\-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()):
       self.errors['mac'] = self.error_class(['Not a MAC address'])
       del cleaned_data['mac']
     m = re.sub("[.:-]", "", mac)
     m = m.lower()
     mac = "%s-%s-%s-%s-%s-%s" % (m[0:2], m[2:4], m[4:6], m[6:8], m[8:10], m[10:])
     cleaned_data['mac'] = mac
   if not found and ip_valid:
     self.errors['content'] = self.error_class(['IP is not within a known range'])
     ip_valid = False
   return cleaned_data
Ejemplo n.º 47
0
 def perform_checking(ip):
     validate_ipv4_address(ip)
     if not all_matching_cidrs(ip, ip_ranges) and ip_ranges:
         raise forms.ValidationError(_('Specified Cluster Static IP is'
                                       'not in valid IP range'))
     try:
         ip_info = novaclient(request).fixed_ips.get(ip)
     except exceptions.UNAUTHORIZED:
         exceptions.handle(
             request, _("Unable to retrieve information "
                        "about fixed IP or IP is not valid."),
             ignore=True)
     else:
         if ip_info.hostname:
             raise forms.ValidationError(
                 _('Specified Cluster Static IP is already in use'))
Ejemplo n.º 48
0
def ip_to_long(value):
    validators.validate_ipv4_address(value)

    lower_validator = validators.MinValueValidator(0)
    upper_validator = validators.MinValueValidator(255)

    value = value.split('.')
    output = 0

    for i in range(0, 4):
        validators.validate_integer(value[i])
        lower_validator(value[i])
        upper_validator(value[i])
        output += long(value[i]) * (256**(3-i))

    return output
Ejemplo n.º 49
0
def validate_proxy(val):
    if val.count(':') != 1:
        raise ValidationError('Invalid address')

    host, port = val.split(':')
    try:
        validate_ipv4_address(host)
    except ValidationError:
        # ip may in fact be a hostname
        # http://www.regextester.com/23
        HOSTNAME_RX = r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$'
        if not re.match(HOSTNAME_RX, host):
            raise ValidationError('Invalid hostname or IP')
    try:
        port = int(port)
    except ValueError:
        raise ValidationError('Invalid port')
Ejemplo n.º 50
0
 def clean(self, value):
     if (value in ADDRESS_CONSTANTS or validate_ipv4_address(value)
         or stun_re.match(value)):
         return value
     else:
         raise forms.ValidationError(
             "This field must be set to an IP address, STUN address "
             "(e.g. stun:stun.freeswitch.org) or \"auto\"/\"auto-nat\".")
Ejemplo n.º 51
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
Ejemplo n.º 52
0
def get_ip_external_detail(ip_addr, source):
    """
        Get documents matching ip_addr and source
    """
    try:
        validate_ipv4_address(ip_addr)
    except ValidationError:
        return 400, {'status': 'Bad Request', 'code': 400, 'message': 'Not a valid IPV4'}

    results = []

    if ImplementationFactory.instance.is_implemented('ReputationDaoBase'):
        try:
            results = ImplementationFactory.instance.get_singleton_of('ReputationDaoBase').get_ip_external_details(ip_addr, source)
        except ReputationDaoException:
            pass

    return 200, results
Ejemplo n.º 53
0
def get_ip_external_reputation(ip_addr):
    """
        External checks
    """
    try:
        validate_ipv4_address(ip_addr)
    except ValidationError:
        return 400, {'status': 'Bad Request', 'code': 400, 'message': 'Not a valid IPV4'}

    results = []

    if ImplementationFactory.instance.is_implemented('ReputationDaoBase'):
        try:
            results = ImplementationFactory.instance.get_singleton_of('ReputationDaoBase').get_ip_external_reputations(ip_addr)
        except ReputationDaoException:
            pass

    return 200, results
Ejemplo n.º 54
0
    def _decorated(view, request, *args, **kwargs):
        if not settings.ENABLE_LIMIT_IPADDRESS:
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if request.method in ["DELETE", "POST"]:
            ipaddress = request.data.get('ipaddress', '')
            if not ipaddress:
                error_msg = 'IP address can not be empty.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            try:
                validate_ipv4_address(ipaddress.replace('*', '1'))
            except ValidationError:
                error_msg = "IP address invalid."
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        return func(view, request, *args, **kwargs)
Ejemplo n.º 55
0
 def perform_checking(ip):
     django_validator.validate_ipv4_address(ip)
     if not netaddr.all_matching_cidrs(ip, ip_ranges) and ip_ranges:
         raise forms.ValidationError(_("Specified Cluster Static IP is" " not in valid IP range"))
     try:
         ip_info = nova.novaclient(request).fixed_ips.get(ip)
     except exceptions.UNAUTHORIZED:
         LOG.error("Error to get information about IP address" " using novaclient")
         exceptions.handle(
             request, _("Unable to retrieve information " "about fixed IP or IP is not valid."), ignore=True
         )
     except exceptions.NOT_FOUND:
         msg = "Could not found fixed ips for ip %s" % (ip,)
         LOG.error(msg)
         exceptions.handle(request, msg, ignore=True)
     else:
         if ip_info.hostname:
             raise forms.ValidationError(_("Specified Cluster Static IP is already in use"))
Ejemplo n.º 56
0
    def test_filling_IPAddressField(self):
        try:
            from test.generic.models import DummyGenericIPAddressFieldModel as IPModel
        except ImportError:
            from test.generic.models import DummyIPAddressFieldModel as IPModel

        obj = mommy.make(IPModel)
        field = IPModel._meta.get_field('ipv4_field')
        self.assertIsInstance(field, GenericIPAddressField)
        self.assertIsInstance(obj.ipv4_field, string_types)

        validate_ipv4_address(obj.ipv4_field)

        if hasattr(obj, 'ipv6_field'):
            self.assertIsInstance(obj.ipv6_field, string_types)
            self.assertIsInstance(obj.ipv46_field, string_types)

            validate_ipv6_address(obj.ipv6_field)
            validate_ipv46_address(obj.ipv46_field)
Ejemplo n.º 57
0
    def _expand_netloc(cls, host, port=None):
        """
        Returns a list of possible domain expansions for ``host`` and ``port``.

        ``host`` is a hostname like ``'example.com'``.
        ``port`` is a port number like 8000, or None.

        Expansions are ordered from highest to lowest preference and may
        include wildcards. Examples::

        >>> AliasManager._expand_netloc('www.example.com')
        ['www.example.com', '*.example.com', '*.com', '*']

        >>> AliasManager._expand_netloc('www.example.com', 80)
        ['www.example.com:80', 'www.example.com',
         '*.example.com:80', '*.example.com',
         '*.com:80', '*.com',
         '*:80', '*']
        """
        if not host:
            raise ValueError(u"Invalid host: %s" % host)

        try:
            validate_ipv4_address(host)
            bits = [host]
        except ValidationError:
            # Not an IP address
            bits = host.split('.')

        result = []
        for i in xrange(0, (len(bits) + 1)):
            if i == 0:
                host = '.'.join(bits[i:])
            else:
                host = '.'.join(['*'] + bits[i:])
            if port:
                result.append("%s:%s" % (host, port))
            result.append(host)
        return result