def associateModels(self): self.scan_ports = [1080, 82, 3128, 3129, 6088, 808, 8080, 8081, 8088, 8090, 8090, 8118, 8123, 8888, 9080, 9999, 3130, 8000, 8082, 9999] self.tableViewIpRangeModel = QStandardItemModel(0, len(self.scan_ports) + 1, self) self.tableViewIpRangeModel.setHeaderData(0, Qt.Horizontal, 'cidr') for i, port in enumerate(self.scan_ports): self.tableViewIpRangeModel.setHeaderData(i + 1, Qt.Horizontal, port) self.tableView.setModel(self.tableViewIpRangeModel) response = IpAsnRangeDoc().search().query('match', owner='amazon.com').execute() total_ip_count = 0 for itm in response: for iprange in itm['ranges']: total_ip_count += iprange['ip_count'] row = [QStandardItem(str(iprange['cidr']))] for _ in range(len(self.scan_ports)): row.append(QStandardItem(str(0))) self.ipranges[IpRange(iprange['cidr'])] = row self.tableViewIpRangeModel.appendRow(self.ipranges[IpRange(iprange['cidr'])]) self.ipCountLabel.setText('%s total ips.' % total_ip_count) self.progressBar.setMinimum(0) self.progressBar.setMaximum(total_ip_count)
def create_network(self, name, cidr, dhcp=True): conn = self.conn try: range = IpRange(cidr) except TypeError: print("Invalid Cidr %s.Leaving..." % cidr) return netmask = IPNetwork(cidr).netmask gateway = range[1] if dhcp: start = range[2] end = range[-2] dhcpxml = """<dhcp> <range start='%s' end='%s'/> </dhcp>""" % (start, end) else: dhcpxml = '' networkxml = """<network><name>%s</name> <forward mode='nat'> <nat> <port start='1024' end='65535'/> </nat> </forward> <domain name='%s'/> <ip address='%s' netmask='%s'> %s </ip> </network>""" % (name, name, gateway, netmask, dhcpxml) new_net = conn.networkDefineXML(networkxml) new_net.setAutostart(True) new_net.create()
def create_network(self, name, cidr=None, dhcp=True, nat=True, domain=None, plan='kvirt', pxe=None, vlan=None): conn = self.conn project = self.project region = self.region body = {'name': name} body['autoCreateSubnetworks'] = True if cidr is not None else False conn.networks().insert(project=project, body=body).execute() timeout = 0 while True: if timeout > 60: return { 'result': 'failure', 'reason': 'timeout waiting for network to be ready' } try: if cidr is not None: try: IpRange(cidr) except TypeError: return { 'result': 'failure', 'reason': "Invalid Cidr %s" % cidr } subnetbody = { 'name': name, "ipCidrRange": cidr, "network": "projects/%s/global/networks/%s" % (project, name), 'region': "projects/%s/regions/%s" % (project, region) } conn.subnetworks().insert(region=region, project=project, body=subnetbody).execute() allowed = {"IPProtocol": "tcp", "ports": ["22"]} firewallbody = { 'name': 'allow-ssh-%s' % name, 'network': 'global/networks/%s' % name, 'sourceRanges': ['0.0.0.0/0'], 'allowed': [allowed] } conn.firewalls().insert(project=project, body=firewallbody).execute() break except Exception as e: print(e) timeout += 5 time.sleep(5) common.pprint("Waiting for network to be ready", color='green') return {'result': 'success'}
def gather_data(): psk = prompt('Enter PSK', default=random_string(32)) dns_prime = check_ip('Primary DNS', '8.8.8.8') dns_second = check_ip('Secondary DNS', '8.8.4.4') local_cidr = check_cidr('VPN IPv4 local CIDR', '10.11.12.0/24') local_ip = IpRange(local_cidr)[1] local_ip_range = IpRange(local_cidr)[10] + '-' + IpRange(local_cidr)[ len(IpRange(local_cidr)) - 5] duo = check_duo() api_key = prompt('Foxpass API Key') radius_secret = random_string(16) public_ip = urlopen( 'http://169.254.169.254/latest/meta-data/public-ipv4').read() private_ip = urlopen( 'http://169.254.169.254/latest/meta-data/local-ipv4').read() holders = { '<PSK>': psk, '<DNS_PRIMARY>': dns_prime, '<DNS_SECONDARY>': dns_second, '<IP_RANGE>': local_ip_range, '<LOCAL_IP>': local_ip, '<LOCAL_SUBNET>': local_cidr, '<PUBLIC_IP>': public_ip, '<PRIVATE_IP>': private_ip, '<RADIUS_SECRET>': radius_secret, '<API_KEY>': api_key, '<DUO_API_HOST>': duo[0], '<DUO_IKEY>': duo[1], '<DUO_SKEY>': duo[2] } file_list = { 'ipsec.secrets': '/etc/', 'iptables.rules': '/etc/', 'options.xl2tpd': '/etc/ppp/', 'xl2tpd.conf': '/etc/xl2tpd/', 'ipsec.conf': '/etc/', 'radius_agent_config.py': '/opt/bin/', 'servers': '/etc/radiusclient/' } return {'holders': holders, 'file_list': file_list}
def check_ip(target, default=None): while True: try: ip = prompt("Enter %s: " % target, default) str(IpRange(ip)) except TypeError: print "%s is not a valid IP." % ip else: return ip
def check_ip(target, default=None): while True: try: ip = prompt('Enter {}: '.format(target), default) str(IpRange(ip)) except TypeError: print('{} is not a valid IP.'.format(ip)) else: return ip
def ip_in_iplist(ip, ip_list): if ip in ip_list: return True ranges = [_ip for _ip in ip_list if '-' in _ip] for range in ranges: split_res = range.split('-') ip_range = IpRange(split_res[0], split_res[1]) if ip in ip_range: return True return False
def create_network(self, name, cidr=None, dhcp=True, nat=True, domain=None, plan='kvirt', pxe=None, vlan=None): conn = self.conn if cidr is not None: try: IpRange(cidr) except TypeError: return {'result': 'failure', 'reason': "Invalid Cidr %s" % cidr} vpc = conn.create_vpc(CidrBlock=cidr) vpcid = vpc['Vpc']['VpcId'] conn.create_subnet(CidrBlock=cidr, VpcId=vpcid) if nat: conn.create_internet_gateway() return {'result': 'success'}
def get_public_ips(self): result = [] for gatewayInterface in self.get_interfaces('uplink'): for subnetParticipation in gatewayInterface.get_SubnetParticipation(): ipRanges = subnetParticipation.get_IpRanges() if ipRanges: for ipRange in ipRanges.get_IpRange(): startAddress = ipRange.get_StartAddress() endAddress = ipRange.get_EndAddress() addresses = IpRange(startAddress, endAddress) for address in addresses: result.append(address) result = list(set(result)) return result
def main(): admin_username = raw_input("Enter Administrator Username [admin]:") admin_password = raw_input("Enter Administrator Password [22222]:") while True: ip_start = raw_input("Enter IP start:") if not ip_start: print '\033[1;31mIP Start Required\033[1;m' else: if validate_ip(ip_start): break else: print '\033[1;31mThis is not a valid IPv4 address\033[1;m' while True: ip_stop = raw_input("Enter IP stop:") if not ip_stop: print '\033[1;31mIP Stop Required\033[1;m' else: if validate_ip(ip_stop): break else: print '\033[1;31mThis is not a valid IPv4 address\033[1;m' if not admin_username: admin_username = "******" if not admin_password: admin_password = "******" #get the ip_start and stop and get a ip range r = IpRange(ip_start, ip_stop) for ip in r: check = Aastra_Check(ip, admin_username, admin_password) if check.check(): check.get_local_file() else: print "%s Is not an Aastra SIP Device" % ip
def execute_analysis(self, ipv4): analysis = ASNAnalysis() ipv4.add_analysis(analysis) analysis.details = None logging.debug("scanning ASN routes for {0}".format(ipv4.value)) m = re.match( r'^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$', ipv4.value) if m is None: logging.error("regex failed for ipvr {0}".format(ipv4.value)) return (a, b, c, d) = m.groups() logging.debug("performing ASN lookup for {0}".format(ipv4.value)) for key in [ '{0}.{1}.{2}'.format(a, b, c), '{0}.{1}'.format(a, b), '{0}'.format(a) ]: try: for (cidr, owner_id) in self.internet[key]: cidr_object = IpRange(cidr) if ipv4.value in cidr_object: logging.debug( "found ASN {0} for ipv4 {1} in network {2}".format( owner_id, ipv4.value, cidr)) analysis.details = { KEY_CIDR: cidr, KEY_ASN: owner_id, KEY_ORGANIZATION: self.owners[owner_id] } return except KeyError: pass
def config_vpn(data): mfa_type = '' duo_api_host = '' duo_ikey = '' duo_skey = '' okta_hostname = '' okta_apikey = '' if 'mfa_type' in data: mfa_type = data['mfa_type'] if 'duo_config' in data: duo_api_host = data['duo_config'].get('api_host') duo_ikey = data['duo_config'].get('ikey') duo_skey = data['duo_config'].get('skey') if 'okta_config' in data: okta_hostname = data['okta_config'].get('hostname') okta_apikey = data['okta_config'].get('apikey') local_ip_range = IpRange(data['local_cidr'])[10] + '-' + IpRange( data['local_cidr'])[len(IpRange(data['local_cidr'])) - 5] local_ip = IpRange(data['local_cidr'])[1] holders = { '<PSK>': data['psk'], '<DNS_PRIMARY>': data['dns_primary'], '<DNS_SECONDARY>': data['dns_secondary'], '<IP_RANGE>': local_ip_range, '<LOCAL_IP>': local_ip, '<LOCAL_SUBNET>': data['local_cidr'], '<PUBLIC_IP>': data['public_ip'], '<PRIVATE_IP>': data['private_ip'], '<INTERFACE>': data['interface'], '<RADIUS_SECRET>': data['radius_secret'], '<API_KEY>': data['foxpass_api_key'], '<REQUIRE_GROUPS>': ','.join(data['require_groups']) if 'require_groups' in data else '', '<MFA_TYPE>': mfa_type, '<DUO_API_HOST>': duo_api_host, '<DUO_IKEY>': duo_ikey, '<DUO_SKEY>': duo_skey, '<OKTA_HOSTNAME>': okta_hostname, '<OKTA_APIKEY>': okta_apikey } file_list = { 'ipsec.secrets': '/etc/', 'iptables.rules': '/etc/', 'options.xl2tpd': '/etc/ppp/', 'xl2tpd.conf': '/etc/xl2tpd/', 'ipsec.conf': '/etc/', 'foxpass-radius-agent.conf': '/etc/', 'servers': '/etc/radiusclient/' } templates = '/opt/templates' files = {} for file in file_list.iterkeys(): path = '%s/%s' % (templates, file) files[file] = open(path, 'r').read() for file, source in files.iteritems(): dest = open(file_list[file] + file, 'w') for orig, repl in holders.iteritems(): source = source.replace(orig, repl) dest.write(source) dest.close() commands = ['xl2tpd', 'ipsec', 'fail2ban', 'foxpass-radius-agent'] call(['/sbin/sysctl', '-p']) # set /etc/ipsec.secrets to be owned and only accessible by root # chmod 0600 is r/w owner # chown 0 is set user to root chmod('/etc/ipsec.secrets', 0600) chown('/etc/ipsec.secrets', 0, 0) call('/sbin/iptables-restore < /etc/iptables.rules', shell=True) for command in commands: call(['service', command, 'stop'], shell=False) call(['service', command, 'start'], shell=False)
def iprangelistappend(match, rangelist): rangelist.ips += (IpRange(match.prefix), ) return match.prefix, match.owner
def config_vpn(data): context = { 'PSK': data['psk'], 'DNS_PRIMARY': data['dns_primary'], 'DNS_SECONDARY': data['dns_secondary'], 'PUBLIC_IP': data['public_ip'], 'PRIVATE_IP': data['private_ip'], 'INTERFACE': data['interface'], 'RADIUS_SECRET': data['radius_secret'], 'API_KEY': data['foxpass_api_key'], 'API_HOST': data.get('foxpass_api_url', 'https://api.foxpass.com') } if 'require_groups' in data: context['REQUIRE_GROUPS'] = ','.join(data['require_groups']) if 'mfa_type' in data: context['MFA_TYPE'] = data.get('mfa_type') if 'duo_config' in data: context.update({ 'DUO_API_HOST': data['duo_config'].get('api_host'), 'DUO_IKEY': data['duo_config'].get('ikey'), 'DUO_SKEY': data['duo_config'].get('skey') }) if 'okta_config' in data: context.update({ 'OKTA_HOSTNAME': data['okta_config'].get('hostname'), 'OKTA_APIKEY': data['okta_config'].get('apikey') }) l2tp_cidr = data.get('l2tp_cidr') if l2tp_cidr: l2tp_ip_range_obj = IpRange(data['l2tp_cidr']) l2tp_ip_range = "{}-{}".format(l2tp_ip_range_obj[10], l2tp_ip_range_obj[-6]) l2tp_local_ip = l2tp_ip_range_obj[1] context.update({ 'L2TP_IP_RANGE': l2tp_ip_range, 'L2TP_LOCAL_IP': l2tp_local_ip, 'L2TP_CIDR': l2tp_cidr, }) xauth_cidr = data.get('xauth_cidr') if xauth_cidr: xauth_ip_range_obj = IpRange(data['xauth_cidr']) xauth_ip_range = "{}-{}".format(xauth_ip_range_obj[10], xauth_ip_range_obj[-6]) xauth_local_ip = xauth_ip_range_obj[1] context.update({ 'XAUTH_IP_RANGE': xauth_ip_range, 'XAUTH_CIDR': xauth_cidr, }) file_list = { 'ipsec.secrets': '/etc/', 'iptables.rules': '/etc/', 'options.xl2tpd': '/etc/ppp/', 'xl2tpd.conf': '/etc/xl2tpd/', 'ipsec.conf': '/etc/', 'foxpass-radius-agent.conf': '/etc/', 'servers': '/etc/radiusclient/', 'pam_radius_auth.conf': '/etc/' } # initialize jinja to process conf files env = Environment(loader=FileSystemLoader('/opt/templates'), keep_trailing_newline=True) files = {} for (filename, dir) in file_list.items(): path = os.path.join(dir, filename) template = env.get_template(filename) with open(path, "w") as f: rendered = template.render(**context) f.write(rendered) commands = ['xl2tpd', 'ipsec', 'foxpass-radius-agent'] call(['/sbin/sysctl', '-p']) # set /etc/ipsec.secrets and foxpass-radius-agent.conf to be owned and only accessible by root # chmod 0o600 is r/w owner # chown 0 is set user to root # chown 65534 is set user to nobody:nogroup chmod('/etc/ipsec.secrets', 0o600) chown('/etc/ipsec.secrets', 0, 0) chmod('/etc/foxpass-radius-agent.conf', 0o600) chown('/etc/foxpass-radius-agent.conf', 65534, 65534) call('/sbin/iptables-restore < /etc/iptables.rules', shell=True) call(['/usr/bin/systemctl', 'enable', 'ipsec.service'], shell=False) for command in commands: call(['/usr/bin/systemctl', 'stop', command], shell=False) call(['/usr/bin/systemctl', 'start', command], shell=False)
def load_csv_file(self): line_number = 0 with open(self.csv_file, 'r', encoding=self.csv_file_encoding) as fp: reader = csv.reader(fp) header = next(reader) # skip the header line_number += 1 skip_mode = True # state variable, to skip over invalid network specs current_network = None while True: try: row = next(reader) line_number += 1 except Exception as e: logging.debug( "unable to read line {0} from {1}: {2}".format( line_number, self.csv_file, str(e))) break except StopIteration: break try: # network specifications are two columns if len(row) < 2: continue if len(row) == 2: (count, network) = row if network.strip() == '': continue if network.startswith('000.000.000.000'): skip_mode = True continue else: m = re.match( r'^([0-9]{3}\.[0-9]{3}\.[0-9]{3}\.[0-9]{3})\s+-\s+(.*)$', network) if m is None: #logging.debug("unable to parse network spec out of {0}".format(network)) current_network = None continue network = m.group(1) name = m.group(2) # turn the nnn.nnn.nnn.nnn into an actual IP address m = re.match( r'([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})$', network) (a, b, c, d) = m.groups() network = '{0}.{1}.{2}'.format( str(int(a)), str(int(b)), str(int(c))) cidr = IpRange('{0}.0/24'.format( network)) # assuming they are all /24 specs current_network = IPDBNetwork(network, name, cidr) self.networks.append(current_network) skip_mode = False #logging.debug("loaded {0}".format(current_network)) continue if len(row) != 8: logging.debug( "invalid row count {0} for row {1}".format( len(row), ','.join(row))) continue (count, network, host, _type, division, location, name, comment) = row # skipping over assets assigned to 0.0.0.0 network # I assume this is the "these assets are not on the network" flag for networking group if skip_mode: continue if current_network is None: #logging.debug("current_network is not set while parsing {0}".format(','.join(row))) continue try: ipv4 = str(int(host)) except Exception as e: #logging.debug("value {0} specified for host column is invalid in {1}: {2}".format( #host, ','.join(row), str(e))) continue ipv4 = '{0}.{1}'.format(current_network.network, ipv4) assignment = IPDBAssignment(current_network, ipv4, _type, division, location, name, comment) #if ipv4 in self.assignments: #logging.warning("duplicate ipv4 assignment for {0}".format(ipv4)) self.assignments[ipv4] = assignment #logging.debug("loaded {0}".format(assignment)) except Exception as e: logging.debug("trouble reading ipbd file: {0}".format( str(e))) continue logging.debug( "loaded {0} ipdb networks and {1} ipdb assignments".format( len(self.networks), len(self.assignments)))
def create_network(self, name, cidr=None, dhcp=True, nat=True, domain=None, plan='kvirt', pxe=None, vlan=None): if nat: externalnets = [ n for n in self.neutron.list_networks()['networks'] if n['router:external'] ] externalnet_id = externalnets[0]['id'] if externalnets else None routers = [ router for router in self.neutron.list_routers()['routers'] if router['name'] == 'kvirt' ] router_id = routers[0]['id'] if routers else None try: IpRange(cidr) except TypeError: return {'result': 'failure', 'reason': "Invalid Cidr %s" % cidr} neutron = self.neutron network_id = None networks = { net['name']: net['id'] for net in neutron.list_networks()['networks'] } if name not in networks: network = {'name': name, 'admin_state_up': True} network = neutron.create_network({'network': network}) network_id = network['network']['id'] tenant_id = network['network']['tenant_id'] else: common.pprint("Network already there. Creating subnet", color='blue') if cidr is not None: if network_id is None: network_id = networks[name] cidrs = [ s['cidr'] for s in neutron.list_subnets()['subnets'] if s['network_id'] == network_id ] if cidr not in cidrs: subnet = { 'name': cidr, 'network_id': network_id, 'ip_version': 4, "cidr": cidr, 'enable_dhcp': dhcp } subnet = neutron.create_subnet({'subnet': subnet}) subnet_id = subnet['subnet']['id'] tenant_id = subnet['subnet']['tenant_id'] else: common.pprint("Subnet already there. Leaving", color='blue') return {'result': 'success'} if nat: if externalnet_id is not None: if router_id is None: router = {'name': 'kvirt', 'tenant_id': tenant_id} router['external_gateway_info'] = { "network_id": externalnet_id, "enable_snat": True } router = neutron.create_router({'router': router}) router_id = router['router']['id'] neutron.add_interface_router(router_id, {'subnet_id': subnet_id}) return {'result': 'success'}
def hosts(self): '''This method returns a list of hosts within the provided subnet''' return IpRange(self.ipaddress + '/' + self.mask)