コード例 #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)
コード例 #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"
コード例 #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.")
コード例 #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)
コード例 #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)
コード例 #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')
コード例 #7
0
def validate_ip_bool(address):
    try:

        validate_ipv4_address(address)
        return True
    except ValidationError:
        return False
コード例 #8
0
ファイル: ip_address.py プロジェクト: BinetReseau/dnsapp
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
コード例 #9
0
ファイル: utils.py プロジェクト: 42cc/django-hitcount
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
コード例 #10
0
ファイル: _config.py プロジェクト: reyesdark/ragnarok
    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]))
コード例 #11
0
ファイル: forms.py プロジェクト: CarlesLlobet/CoSA
    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'])))
コード例 #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"
コード例 #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, "")
コード例 #14
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, "")
コード例 #15
0
ファイル: handlers.py プロジェクト: echodaemon/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 "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, "")
コード例 #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')
コード例 #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
コード例 #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
コード例 #19
0
ファイル: forms.py プロジェクト: yrenyi0603/website1
    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)
コード例 #20
0
ファイル: fields.py プロジェクト: qlw/murano-dashboard
 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)
         )
コード例 #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)
コード例 #22
0
ファイル: records.py プロジェクト: BeryJu/supervisr
 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
コード例 #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.'))
コード例 #24
0
ファイル: views.py プロジェクト: Amen06/freedoge
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
コード例 #25
0
ファイル: forms.py プロジェクト: ZhipengJia/djcode
 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
コード例 #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
コード例 #27
0
ファイル: models.py プロジェクト: zhuomingliang/scirius
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')
コード例 #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
コード例 #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
コード例 #30
0
ファイル: tools.py プロジェクト: ctrl-alt-d/django-aula
def getClientAdress( request ):
    
    ip = request.get_host()
    
    try:
        validate_ipv4_address( ip )
    except ValidationError:
        ip = ''
    
    return ip
コード例 #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
コード例 #32
0
ファイル: middleware.py プロジェクト: crodjer/mirosubs
 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
コード例 #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)
コード例 #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)))
コード例 #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)
コード例 #36
0
ファイル: middleware.py プロジェクト: MechanisM/mirosubs
 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
コード例 #37
0
ファイル: tools.py プロジェクト: moiatjda/django-aula
def getClientAdress(request):

    ip = request.get_host()

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

    return ip
コード例 #38
0
ファイル: inetnumadmin.py プロジェクト: Rafiot/contactdb
 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')
コード例 #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
コード例 #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
コード例 #41
0
ファイル: forms.py プロジェクト: CarlesLlobet/CoSA
 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']))
コード例 #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')
コード例 #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
コード例 #44
0
    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)
コード例 #45
0
ファイル: views.py プロジェクト: zehome/claritick
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))
コード例 #46
0
ファイル: forms.py プロジェクト: centran/ipifier
 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
コード例 #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'))
コード例 #48
0
ファイル: models.py プロジェクト: Gluejar/libraryauth
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
コード例 #49
0
ファイル: models.py プロジェクト: awesome-python/scirius
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')
コード例 #50
0
ファイル: forms.py プロジェクト: justhamade/django-pbx
 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\".")
コード例 #51
0
ファイル: decorators.py プロジェクト: aclysma/django-axes
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
コード例 #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
コード例 #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
コード例 #54
0
ファイル: device_trusted_ip.py プロジェクト: haiwen/seahub
    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)
コード例 #55
0
ファイル: fields.py プロジェクト: qlw/murano-dashboard
 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"))
コード例 #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)
コード例 #57
0
ファイル: models.py プロジェクト: ecometrica/django-multisite
    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