def _sanity_check(value, field):
        if field == 'priority':
            try:
                if isinstance(value, int) and value >= 0 and value < 65536:
                    return value
            except:
                return value

        if field == 'port':
            if '-' in value and value != '0-65535':
                first, second = value.split('-')
                if first.isdigit() and second.isdigit():
                    return value
            elif value.isdigit():
                return value
            return '*'  # 'ANY' or '*' or '0-65535':

        if field == 'dl_type':
            if value.upper() in ['ARP', 'IPv4', 'IPv6']:
                return value.upper()
            return 'IPv4'

        if field == 'ipv4':
            if '-' in value:
                first, second = value.split('-')
                if second.isdigit():
                    second = first[:first.rindex('.') + 1] + second
                if valid_ipv4(first) and valid_ipv4(second):
                    return first + '-' + second
            if valid_glob(value):
                return str(glob_to_cidrs(value)[0]).replace('/32', '')
            if valid_ipv4(value) or \
             ('/'in value and valid_ipv4(value[:value.find('/')])):
                return value.replace('/32', '')
            return '*'  # 'ANY'

        if field == 'nw_proto':
            if value.upper() in ['TCP', 'UDP', 'ICMP', 'ICMPv6']:
                return value.upper()
            return 'TCP'

        if field == 'direction':
            if value.upper() in ['IN']:
                return 'IN'
            if value.upper() in ['OUT']:
                return 'OUT'
            return 'IN'

        if field == 'action':
            if value.upper() in ['DENY', 'REJECT']:
                return 'DENY'
            if value.upper() in ['ALLOW', 'ACCEPT']:
                return 'ALLOW'
            return 'DENY'
Exemple #2
0
def _convert_ipstring_to_ipn(ipstring):
    """Transform a single ip string into a list of IPNetwork objects."""
    if netaddr.valid_glob(ipstring):
        ipns = netaddr.glob_to_cidrs(ipstring)
    else:
        try:
            ipns = [netaddr.IPNetwork(ipstring)]
        except netaddr.AddrFormatError:
            msg = (_('Invalid IP access string %s.') % ipstring)
            LOG.error(msg)
            raise exception.GPFSGaneshaException(msg)
    return ipns
Exemple #3
0
 def clean_ip_networks(self):
     ip_networks = self.cleaned_data["ip_networks"]
     ip_networks = ip_networks.replace(" ", "").replace("\r\n","")
     ip_networks_as_list = [cidr for cidr in ip_networks.split("," )]
     cleaned_networks_list = []
     for cidr in ip_networks_as_list:
         if cidr:
             if cidr != ",":
                 try:  
                     cidr_as_glob = cidr_to_glob("%s" % cidr)
                     if valid_glob(cidr_as_glob):
                         cleaned_networks_list.append(cidr)
                     else:
                         raise forms.ValidationError(_("%s is not a valid ip range." % cidr))
                 except:
                     raise forms.ValidationError(_("%s is not a valid ip range." % cidr))
             else: 
                 pass
     return ','.join(cleaned_networks_list)
Exemple #4
0
 def clean_ip_networks(self):
     ip_networks = self.cleaned_data["ip_networks"]
     ip_networks = ip_networks.replace(" ", "").replace("\r\n", "")
     ip_networks_as_list = [cidr for cidr in ip_networks.split(",")]
     cleaned_networks_list = []
     for cidr in ip_networks_as_list:
         if cidr:
             if cidr != ",":
                 try:
                     cidr_as_glob = cidr_to_glob("%s" % cidr)
                     if valid_glob(cidr_as_glob):
                         cleaned_networks_list.append(cidr)
                     else:
                         raise forms.ValidationError(
                             _("%s is not a valid ip range." % cidr))
                 except:
                     raise forms.ValidationError(
                         _("%s is not a valid ip range." % cidr))
             else:
                 pass
     return ','.join(cleaned_networks_list)
Exemple #5
0
def test_invalid_glob():
    assert not valid_glob('1.1.1.a')
    assert not valid_glob('1.1.1.1/32')
    assert not valid_glob('1.1.1.a-b')
    assert not valid_glob('1.1.a-b.*')
Exemple #6
0
def main():
    global run_local
    global local_file
    global domain
    global onlyDNSSEC
    global autosave
    returned_records = []
    name_servers = []
    domain = None
    start = None
    ns_server = None
    request_timeout = 7.0
    out_file = None
    once = False
    onlyDNSSEC = False
    local_file = ''
    run_local = False
    autosave = False
    
    try:
        options, args = getopt.getopt(sys.argv[1:], 'hd:n:o:l:s:',
                                      ['help',
                                      'domain=',
                                      'name_server=',
                                      'output=',
                                      'start=',
                                      'once',
                                      'dnssec',
                                      'local=',
                                      'autosave',
                                      'lifetime='])

    except getopt.GetoptError:
        print_error("Wrong Option Provided!")
        usage()

    for opt, arg in options:
        if opt in ('-d', '--domain'):
            domain = arg

        elif opt in ('-n', '--name_server'):
            # Check if we got an IP or a FQDN
            if netaddr.valid_glob(arg):
                ns_server = arg
            else:
                # Resolve in the case if FQDN
                answer = socket_resolv(arg)
                # Check we actualy got a list
                if len(answer) > 0:
                    # We will use the first IP found as the NS
                    ns_server = answer[0][2]
                else:
                    # Exit if we cannot resolve it
                    print_error("Could not resolve NS server provided")
                    sys.exit(1)

        elif opt in ('-o', '--output'):
            out_file = arg

        elif opt in ('-s', '--start'):
            start = arg

        elif opt in ('--once'):
            once = True

        elif opt in ('--dnssec'):
            onlyDNSSEC = True

        elif opt in ('l', '--lifetime'):
            request_timeout = float(arg)

        elif opt in ('-h'):
            usage()

        elif opt in ('--local'):
            local_file = set(open(arg, 'r').read().split())
            run_local = True

        elif opt in ('--autosave'):
            autosave = True

    print "**************************************************"
    print "Zone: ", domain, " Starting point: ", start

    if start is None:
        """start = ("0_0.{0}".format(domain))"""
        start = domain

    # Set the resolver
    parent = start.split(".")[1]
    res = DnsHelper(domain, ns_server, request_timeout)

    # Enumerate Name Servers IPv4
    if ns_server is None:
        try:
            print "**************************************************"
            print "Enumerating NS"
            print datetime.datetime.now()
            for ns_rcrd in res.get_ns():
                if ":" not in ns_rcrd[2]:
                    name_servers.append(ns_rcrd[2]) 
                    print('\t {0} {1} {2}'.format(ns_rcrd[0], ns_rcrd[1], ns_rcrd[2]))      
            print datetime.datetime.now()
        except dns.resolver.NoAnswer:
            print_error("Could not Resolve NS Records for {0}".format(domain))
            print datetime.datetime.now()
    else:
        name_servers.append(ns_server)

        
    # Walk the zone  
    try:
        print datetime.datetime.now()
        if once is True:
            regNSEC = get_next(start, name_servers[0], request_timeout)
            if regNSEC is None:
                print "No NSEC found. Try appending a 0 to the hostname."
            else:
                print "next: ", regNSEC

        else:
            print "**************************************************"
            print "Walking the Zone"
            if out_file:
                returned_records.extend(ds_zone_walk(start, name_servers, request_timeout))
            else:
                ds_zone_walk(start, name_servers, request_timeout)
            print datetime.datetime.now()

    except dns.exception.Timeout:
        print_error("A timeout error occurred please make sure you can reach the target DNS Servers")
        print_error("directly and requests are not being filtered. Increase the timeout from {0} second".format(request_timeout))
        print_error("to a higher number with --lifetime <time> option.")
        print datetime.datetime.now()
        # sys.exit(1)

    # if an output file is specified it will write returned results.
    if out_file:
        print_status("Saving records to  file: {0}".format(out_file))
        write_to_file(returned_records, out_file)