Beispiel #1
0
    def host(self, id, hostname, **host_vars):
        vars = self.vars.copy()
        vars.update(host_vars)
        vars.update({
            "vpn_id":
            id,
            "batman_ipv4":
            self.calculate_address("ipv4_network", id),
            "batman_ipv6_global":
            self.calculate_address("ipv6_global_network", id),
            "batman_ipv6_local":
            self.calculate_address("ipv6_local_network", id),
        })

        if self.dhcp:
            begin = self.inventory.ipv4_network.ip + (id << 8) * 10
            vars["dhcp"] = {
                "netmask": str(self.inventory.ipv4_network.netmask()),
                "range_begin": str(ipcalc.IP(begin)),
                "range_end": str(ipcalc.IP(begin + 256 * 10 - 1)),
            }

        if self.icvpn:
            vars["icvpn_ipv4"] = self.calculate_address(
                "icvpn_ipv4_network", (id << 8))
            vars["icvpn_ipv6"] = self.calculate_address(
                "icvpn_ipv6_network", (id << 16))

        vars["ipv6_uplink_own_gateway"] = self.calculate_address(
            "ipv6_uplink_network", (id << 16 * 4) + 1)
        vars["ipv6_uplink_own_vpnserver"] = self.calculate_address(
            "ipv6_uplink_network", (id << 16 * 4) + 2)

        self.hosts.append((hostname, vars))
Beispiel #2
0
 def ipadd(self, one, another):
     version = 6 if (':' in one) else 4
     addr = ipcalc.IP(ipcalc.IP(one).ip +
                      ipcalc.IP(another).ip, version=version)
     if addr.version() == 6:
         return addr.to_compressed()
     else:
         return str(addr)
Beispiel #3
0
def ipinfo(address, netmask):
    """Return information about the ip address and netmask given in in"""
    binary_representation = ipcalc.IP(netmask).bin()
    mask = binary_representation.count('1', 0, len(binary_representation))
    calc = ipcalc.Network(address, mask)
    subnet = str(calc.network())
    broadcast = str(calc.broadcast())
    netclass = ipcalc.IP(address).info()
    if netclass == 'CLASS B':
        octects = subnet.split('.')
        reverse_zone = '%s.%s' % (octects[1], octects[0])
    else:
        octects = subnet.split('.')
        reverse_zone = '%s.%s.%s' % (octects[2], octects[1], octects[0])
    return [subnet, broadcast, reverse_zone]
Beispiel #4
0
def _check_network(clientip, domain):

    if ipcalc.IP(clientip).version() == 4:
        for network in V4LIST:
            if clientip in network:
                log_info("private=accept, network=%s, clientip=%s, query=%s" %
                         (network, clientip, domain))
                return True
    elif ipcalc.IP(clientip).version() == 6:
        for network in V6LIST:
            if clientip in network:
                log_info("private=accept, network=%s, clientip=%s, query=%s" %
                         (network, clientip, domain))
                return True
    log_info("private=reject, clientip=%s, query=%s" % (clientip, domain))
    return False
Beispiel #5
0
def dhcp_log_extract_subnets(log_name, log_path='./logs/'):
    """
    Parses Bro dhcp.log file to find different subnets based on dhcp protocol header information.

    :param log_name: name of the dhcp.log file
    :param log_path: path of the directory where dhcp.log is located
    :return: a list of the different subnetmasks observed in Bro dhcp.log
    """
    dhcp_path = os.path.join(log_path, log_name)

    dhcp_fieldnames = 'ts	uid	id.orig_h	id.orig_p	id.resp_h	id.resp_p	mac	assigned_ip	lease_time	trans_id	subnet_mask'.split()

    ### READ LOG FILE INTO PANDAS DATAFRAME ###
    print("Load CSV into dataframe ...\nCSV path: {}".format(dhcp_path))
    df = pd.read_csv(dhcp_path, sep='\t', comment='#', names=dhcp_fieldnames, dtype=str)
    df = df.dropna(how='all') # to drop comment

    # Dictionary that maps column name to column index (need that as we are going to convert the df to numpy array)
    df_column_dict = {k: v for v, k in enumerate(df.columns.values)}

    subnets = {}

    for df_row in tqdm(df.values, desc='Parsing dataframe rows'):
        current_client_ip = df_row[df_column_dict['id.orig_h']]
        current_subnetmask = df_row[df_column_dict['subnet_mask']]

        addr = ipcalc.IP(current_client_ip, mask=current_subnetmask)
        subnet_with_cidr = str(addr.guess_network())
        if subnet_with_cidr not in subnets:
            subnets.add(subnet_with_cidr)

    return subnets
Beispiel #6
0
def simple():
    ip = ipcalc.IP(IPS.get())
    print '=' * 80 + "\nping " + str(ip) + '\n'
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(cfg.ssh['host'], username = cfg.ssh['login'], password = cfg.ssh['password'], port = cfg.ssh['port'])

    channel = ssh.invoke_shell()
    channel.settimeout(cfg.ssh['timeout'])

    channel.send('telnet ' + cfg.telnet['host'] + '\n')
    time.sleep(5)
    output = channel.recv(1024)
    print output,
    channel.send(cfg.telnet['login'] + '\n')
    time.sleep(1)
    output = channel.recv(1024)
    print output,
    channel.send(cfg.telnet['password'] + '\n')
    time.sleep(1)
    output = channel.recv(1024)
    print output,
    channel.send(XLS.PING % str(ip))
    time.sleep(XLS.SLEEP)
    output = channel.recv(65536)
    print output,

    channel.send('quit\n')
    time.sleep(1)
    output = channel.recv(1024)
    print output

    ssh.close()
Beispiel #7
0
def my_ip_details():
    """
    :return: dictionary, with {address, netmask, broadcast, network}
    """
    i_face = subprocess.Popen("route | grep '^default' | grep -o '[^ ]*$'",
                              shell=True,
                              stdout=subprocess.PIPE,
                              universal_newlines=True).stdout.read()
    print('-----', i_face)

    if not i_face:
        return None
    i_face = i_face.split("\n")
    if len(i_face) > 0:
        i_face = i_face[0].strip()

    ip4_address = ifaddresses(i_face).setdefault(AF_INET, [{'addr': None}])
    if not ip4_address or len(ip4_address) == 0:
        return None
    try:
        ip4_address = ip4_address[0]
        tmp = ipcalc.IP(ip=ip4_address['addr'], mask=ip4_address['netmask'])
        ip4_address['network'] = str(tmp.guess_network())
        ip4_address['address'] = ip4_address['addr']
        ip4_address['interface'] = i_face
        del ip4_address['addr']
        return ip4_address
    except:
        print("unable to fetch connection details")
        return None
Beispiel #8
0
def ip_offset(a, *args, **kw):
    """
    Given an IP address, return the IP at the specified offset.
    """
    if not args:
        return a

    ip_addr = a
    offset = args[0]

    try:
        float(offset)
    except ValueError:
        raise errors.AnsibleFilterError("Specified offset isn't numeric.")

    # Return the dotted quad of the offsetted address.
    return ipcalc.IP(ipcalc.IP(ip_addr).ip + offset).dq
def module_body(current_user, __MODULE_PATH__, __OUTPUT_PATH__, SESSION_ID,
                USERLEVEL, debugging):
    print(info['name'] + '\t' + "An IP Calculator")
    print()
    try:
        ip = str(input("Enter IP Address > "))
        ipc = ipcalc.IP(ip)
        ipn = ipcalc.Network(ip)
        ip_ver = ipc.version()

    except ValueError:
        print("Invalid IP Address!")
        return "Error"

    print("IP Address version                 :: ", ip_ver)
    if ip_ver == 4:
        ipv6 = ipc.to_ipv6()
        print("IP Address v6                      :: ", ipv6)

    elif ip_ver == 6:
        ipv4 = ipc.to_ipv4()
        print("IP Address v4                      :: ", ipv4)

    else:
        print("ERROR: Unsupported or unknown version of IP Address!")

    subnet_size = ipc.subnet()
    print("CIDR subnet size                   :: ", subnet_size)
    flbin = ipc.bin()
    print('Full-length binary                 :: ', flbin)
    flhex = ipc.hex()
    print('Full-length hexadecimal            :: ', flhex)
    iana_alloc_info = ipc.info()
    print('IANA allocation information        :: ', iana_alloc_info)
    compressed = ipc.to_compressed()
    print('Shortest possible compressed form  :: ', compressed)
    ptr_rec = ipc.to_reverse()
    print('PTR record                         :: ', ptr_rec)
    net_size = ipc.size()
    print('Network size                       :: ', net_size)
    broadcast_addr = ipn.broadcast()
    print('Broadcast Address                  :: ', broadcast_addr)
    host_first = ipn.host_first()
    print('First available host in this subnet:: ', host_first)
    host_last = ipn.host_last()
    print('Last available host in this subnet :: ', host_last)
    netmask = ipn.netmask()
    print('Network netmask                    :: ', netmask)
    size = ipn.size()
    print('Number of ip\'s within the network  :: ', size)
    print()
    print(
        API.ShadowSuite(current_user, __MODULE_PATH__, __OUTPUT_PATH__,
                        SESSION_ID, USERLEVEL, debugging).FINISH)
Beispiel #10
0
def isValidIP(ipaddr):
    try:
        bits = len(ipcalc.IP(ipaddr).bin())
    except:
        return 0
    if bits == 32:
        return 4
    elif bits == 128:
        return 6
    else:
        return 0
Beispiel #11
0
    def _resolve(self, dns_request, dns_response, request_info):

        clientip = ipcalc.IP(request_info.client_address[0])
        if clientip.version() == 4:
            for blv4 in self._iplist4:
                if clientip in blv4:
                    raise self.on_detect
        else:
            for blv6 in self._iplist6:
                if clientip in blv6:
                    raise self.on_detect
Beispiel #12
0
    def scan_subnet_details_local(self, session, pmpt, filehand):
        Flag = "F"
        Cap_Cnt = 0
        self.local_vlans_found = 0
        ipPat = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
        network_with_cidr = "NF"
        local_subnet_found = "No"
        for vl in self.vlan_all:
            Flag = "F"
            result, Cap_Cnt, Flag = self.capCiscoRS.CaptureOutput(
                session, "show run interface vlan" + str(vl), 0, Flag, pmpt)
            local_subnet_found = "No"
            if "ip address " in result:
                result = result.split('\n')

            for item in result:
                if "no ip address " in item.lower():
                    local_subnet_found = "No"
                    break
                if "ip address " in item and "." in item:
                    ip_address_with_mask = re.findall(ipPat, item)

                    addr = ipcalc.IP(ip_address_with_mask[0],
                                     mask=ip_address_with_mask[1])
                    network_with_cidr = str(addr.guess_network())
                    local_subnet_found = "Yes"
                    filehand.write("\n" + str(vl) + " Subnet : " +
                                   network_with_cidr + '\n')

                    self.local_vlans_found += 1
                    break
            if local_subnet_found == "No":
                Flag = "F"
                result, Cap_Cnt, Flag = self.capCiscoRS.CaptureOutput(
                    session, "show interface vlan" + str(vl), 0, Flag, pmpt)
                local_subnet_found = "No"
                result = result.split('\n')
                for item in result:

                    if "Internet address is" in item and "." in item:

                        final_subnet = item.replace("Internet address is",
                                                    '').strip()
                        ip = IPNetwork(final_subnet)
                        final_subnet = str(ip.cidr)

                        local_subnet_found = "Yes"
                        filehand.write("\n" + str(vl) + " Subnet : " +
                                       final_subnet + '\n')

                        self.local_vlans_found += 1
                        break
Beispiel #13
0
    def calculate_address(self, key, incr):
        try:
            origin = getattr(self, key)
        except AttributeError:
            return

        address = ipcalc.IP(origin.ip + incr)
        return {
            "address":
            str(address.to_compressed() if origin.v == 6 else address),
            "netmask": str(origin.netmask()),
            "size": origin.subnet(),
        }
Beispiel #14
0
    def _resolve(self, dns_request, dns_response, request_info):

        clientip = ipcalc.IP(request_info.client_address[0])
        if clientip.version() == 4:
            for blv4 in self._iplist4:
                if clientip in blv4:
                    return
        else:
            for blv6 in self._iplist6:
                if clientip in blv6:
                    return

        #if we reached so far than we could not find a matching range so we will stop the processing.
        raise self.on_detect
Beispiel #15
0
    def getoctet(self, value, num, expand=False):
        addr = ipcalc.IP(value)

        if addr.version() == 4 and 0 < num < 5:
            return str(addr).split('.')[num - 1]
        if addr.version() == 6 and 0 < num < 9:
            quad = str(addr).split(':')[num - 1]
            if quad == '0000':
                return 0
            if not expand:
                return quad.lstrip('0')
            else:
                return quad

        return
    def gen_subnet(self, subnet_id, indent=0):
        """Generates config for one subnet"""

        c = self.db.cursor()
        c.execute('SELECT name, vlan, ipv4_txt, ipv4_netmask_txt, '
                  'ipv4_gateway_txt FROM network '
                  'WHERE node_id=?', (subnet_id,))
        name, vlan, ip_cidr, netmask, gateway = c.fetchone()
        ip = ip_cidr.split('/')[0]

        c.execute("""SELECT value FROM option WHERE 
                  name='resv' AND node_id=?""", (subnet_id,))
        resv_rows = c.fetchall()
        resv = 5  # default value
        if len(resv_rows) > 0:
            resv = int(resv_rows[0][0])

        net = ipcalc.Network(ip_cidr)
        range_start = ipcalc.IP(int(net.host_first())+resv)
        range_end = net.host_last()

        c.execute("""SELECT name, value FROM option
            WHERE node_id=? AND name LIKE 'dhcp-%'""", (subnet_id,))
        options = dict(map(lambda x: (x[0][5:], x[1]), c.fetchall()))

        self._print_indented('#@ NET {} {} - VLAN {}'
                             .format(name, ip_cidr, vlan), indent)
        self._print_indented('subnet {} netmask {} {{'
                             .format(ip, netmask), indent)
        self._print_indented('range {} {};'
                             .format(range_start, range_end), indent+1)
        self._print_indented('option routers {};'.format(gateway), indent+1)

        if 'tftp' in options:
            host = options['tftp']
            c = self.db.cursor()
            c.execute('SELECT ipv4_addr_txt FROM '
                      'host WHERE name = ?', (host, ))
            ipv4, = c.fetchone()
            self._print_indented('filename "/tftpboot.img";', indent+1)
            self._print_indented('next-server {};'.format(ipv4), indent+1)
            del options['tftp']

        for option in options.iteritems():
            self._print_indented('{} {};'.format(*option), 1)

        self._print_indented('}\n', indent)
Beispiel #17
0
def _read_network(pnlist):
    global V4LIST, V6LIST

    ipv4 = []
    ipv6 = []

    for line in open(pnlist, "r"):
        ipornet = line.rstrip()
        try:
            version = ipcalc.IP(ipornet).version()
            if version == 4:
                ipv4.append(ipornet)
            elif version == 6:
                ipv6.append(ipornet)
        except:
            pass

    V4LIST = [ipcalc.Network(ip) for ip in ipv4]
    V6LIST = [ipcalc.Network(ip) for ip in ipv6]
Beispiel #18
0
 def __call__(self, ip):
     # Likely to be several sequential hits from offenders and
     # innocents alike
     if self.cm.check(0, ip):
         # Offender was cached
         return True
     if self.cm.check(1, ip):
         # Innocent was cached
         return False
     ipObject = ipcalc.IP(ip)
     # Not found (yet), go through the actual list of networks. If
     # a hit is found, the count for that network is increased and
     # the list is resorted by number of hits, descending. This
     # results in more efficient operation as the more notorious
     # networks get found first.
     for netAndCount in self.networks:
         if netAndCount[0].has_key(ipObject):
             # Offender found
             self.cm.set(0, ip)
             netAndCount[1] += 1
             self.networks.sort(key=lambda x: x[1], reverse=True)
             return True
     self.cm.set(1, ip)
     return False
Beispiel #19
0
    num = 0
    robot_addrs = {}
    address_numbering = {}

    # function to add the address to the numbering
    def noteaddr(name, addr):
        global address_numbering, robot_addrs, num
        if addr in address_numbering:
            robot_addrs[name] = address_numbering[addr]
        else:
            address_numbering[addr] = num
            robot_addrs[name] = num
            num += 1

    for robot in robots:
        addr = ipcalc.IP(robot.find('ip').text.strip())
        mailing_list_name = robot.find('list_name')
        if mailing_list_name is not None:
            mailing_list_name = mailing_list_name.text
            ml_suffixes = [
                'admin', 'bounces', 'confirm', 'join', 'leave', 'owner',
                'request', 'subscribe', 'unsubscribe'
            ]
            noteaddr(mailing_list_name, addr)
            for suffix in ml_suffixes:
                noteaddr(mailing_list_name + '-' + suffix, addr)
        else:
            name = robot.find('name').text.strip()
            noteaddr(name, addr)
    robot_addresses = robot_addrs  # move to global scope
    robot_servers = [None] * len(address_numbering)
Beispiel #20
0
#Asignación del json

ip = test['ip']
mask = test['mask']
domain = test['domain']
dns_server = test['dns_server']
name = test['name']
mac_ap = test['mac_ap']
ap_name = test['ap_name']
range_start = test['range_start']
range_end = test['range_end']
name_wifi = test['name_wifi']

#Subneteo
addr = ipcalc.IP(ip, mask=mask)
network_with_cidr = str(addr.guess_network())
bare_network = network_with_cidr.split('/')[0]
bare_network_cidr = network_with_cidr.split('/')[1]

start_list = range_start.split('.')
end_list = range_end.split('.')
max_pool = abs(int(start_list[3]) - int(end_list[3]))

#Variables
interface = "wlan0"


#Funciones
def createFile():
    subprocess(["touch", "/etc/config/data"])
Beispiel #21
0
def is_known_ip_exception(ip):
    for exception in ip_exceptions:
        if ip == ipcalc.IP(exception):
            return True

    return False
Beispiel #22
0
def evaluate_inetnum_object(inetnum_object, failed_organisation_lookup_write_queue, exceptions_write_queue):
    temp_record = ""
    org_values = ""
    route_values = ""

    split_range = split_ip_range(inetnum_object['inetnum'])
    start_ip = split_range[0]
    end_ip = split_range[1]
    ip_prefix = str(netaddr.iprange_to_cidrs(start_ip, end_ip)[0])

    if is_special_purpose_network(ipcalc.Network(ip_prefix)) or is_known_ip_exception(ipcalc.IP(start_ip)):
        exceptions_write_queue.put(ip_prefix)
        return None
    else:
        for inetnum_key, inetnum_value in inetnum_object.iteritems():
            if inetnum_value is None:
                inetnum_value = "NULL"

                if inetnum_key is "org":
                    org_values = "NULL" + column_delimiter + "NULL" + column_delimiter
            else:
                if inetnum_key is "inetnum":
                    inetnum_value = start_ip + column_delimiter + end_ip + column_delimiter + ip_prefix
                elif inetnum_key is "org":
                    org_info = get_organisation_info(inetnum_value)

                    if org_info is not None:
                        for org_key, org_value in org_info.iteritems():
                            if org_key is not "organisation":
                                org_values = org_values + '"' + str(org_value) + '"' + column_delimiter
                    else:
                        org_values = "NULL" + column_delimiter + "NULL" + column_delimiter
                        failed_organisation_lookup_write_queue.put(inetnum_object)
                elif inetnum_key is not "country":
                    inetnum_value = '"' + inetnum_value + '"'

            temp_record = temp_record + inetnum_value + column_delimiter

        temp_record = temp_record + org_values + route_values
        return temp_record[:-1] + "\n"
Beispiel #23
0
def get_network(ip, netmask=24):
    addr = ipcalc.IP(ip, mask=netmask)
    network_with_cidr = str(addr.guess_network())
    bare_network = network_with_cidr.split('/')[0]
    return addr, network_with_cidr, bare_network
            raise TemplateError(
                'Multiple routers are declared in umbrella.xml .')
extif_enabled = False
intif_enabled = False
ext_address = None
int_address = None
iftypes = ['extif', 'intif', 'pubif', 'secif', 'DMZif', 'vpnif', 'winif']
routerifs = {}
routerifdevs = {}
if router is None:
    # in case there is no router we simulate its pub interface
    # by taking the gateway ip address from the root entry in
    # organization.xml
    gw = metadata.Properties['organization.xml'].xdata.find('ou').find(
        'gateway')
    routerifs['pubif'] = ipcalc.IP(gw.text.strip())
    routerifdevs['pubif'] = 'eth0'
else:
    # fetch router interfaces from xml (used to set default routes on
    # internal subnets)
    routerifdevs = {}
    routerifmacs = {}
    for interface in iftypes:
        t = router.find(interface)
        if t is not None:
            routerifdevs[interface] = t.find('dev').text
            routerifmacs[interface] = t.find('mac').text
            t = t.find('ip')
            if (t is not None) and (t.text is not None and t.text.strip()):
                routerifs[interface] = ipcalc.IP(t.text.strip())
    # Check if the external interfaces are enabled at router
User:               Guodong
Create Date:        2017/4/30
Create Time:        10:46
 """
import IPy

import ipcalc
# https://pypi.python.org/pypi/ipcalc/1.99.0
# Note: ipcalc is a program come from Linux package 'ipcalc'

import pyipcalc

# Another module
# https://pypi.python.org/pypi/pyipcalc/1.0.1

print ipcalc.IP("192.168.1.1")
print ipcalc.Network('192.168.1.0/24')
print ipcalc.Network('192.168.1.0/255.255.255.0')

print pyipcalc.IPNetwork("192.168.1.0/24").ip_network
print pyipcalc.IPNetwork("192.168.1.0/24").subnet()
print pyipcalc.IPNetwork("192.168.1.0/24").network()

ip_str = '''192.168.4.1
192.168.4.3
192.168.4.4
192.168.6.54
192.168.6.55
192.168.6.100
192.168.6.101
'''
User:               Guodong
Create Date:        2017/4/30
Create Time:        10:46
 """
import IPy

import ipcalc
# https://pypi.python.org/pypi/ipcalc/1.99.0
# Note: ipcalc is a program come from Linux package 'ipcalc'

import pyipcalc

# Another module
# https://pypi.python.org/pypi/pyipcalc/1.0.1

print ipcalc.IP("192.168.1.1")
print ipcalc.IP("192.168.1.1/24").info()  # PRIVATE
print ipcalc.IP("124.129.14.90/30").mask  # 30
print ipcalc.IP("124.129.14.90/255.255.255.252").mask  # 30
print ipcalc.Network('123.235.52.106/30').netmask()  # IP('255.255.255.252')
print ipcalc.Network('123.235.52.106/30').network()

print ipcalc.Network('192.168.1.0/24')
print ipcalc.Network('192.168.1.0/255.255.255.0')

print pyipcalc.IPNetwork("192.168.1.0/24").mask()  # better than ipcalc
print pyipcalc.IPNetwork("192.168.1.0/24").network()

ip_str = '''192.168.4.1
192.168.4.3
192.168.4.4
Beispiel #27
0
intnets.pop('intif', None)

# internal networks as strings
intnets_str = {}
for ifname, ifnet in intnets.iteritems():
    intnets_str[ifname] = str(ifnet.network()) + '/' + str(ifnet.mask)

# internal network interface names tuple
intnet_ifs = tuple(intnets.iterkeys())

# check that all the internal networks are part of the whole network
intnets_copy = intnets
intnets_copy.pop("vpnif", None)
for network in intnets_copy.itervalues():
    if not network in wholenet:
        raise TemplateError('The network '+str(network)+'/'+str(network.mask)+\
                            ' is not part of the whole network '+str(wholenet)+\
                            '/'+str(network.mask)+' .')

# retrieve dhcp ranges
pub_dhcp = metadata.Properties['umbrella.xml'].xdata.find('pub_dhcp')
if pub_dhcp is not None:
    pub_dhcp = [
        ipcalc.IP(pub_dhcp.find('start').text),
        ipcalc.IP(pub_dhcp.find('end').text)
    ]
    if long(pub_dhcp[0]) > long(pub_dhcp[1]):
        raise TemplateError(
            'The start DHCP address must be smaller or equal to the end DHCP address in <pub_dhcp> section of umbrella.xml.'
        )