def get_security_groups_endpoints(self): lst_ret = [] all_addresses = [] for sec_grp in self.groups: for dict_addr in self.private_ip_addresses: # Public description = "Inteface: SubnetId: {} NetworkInterfaceId: {}- '{}'".format( self.subnet_id, self.id, self.description) dict_ret = { "sg_id": sec_grp["GroupId"], "sg_name": sec_grp["GroupName"], "description": description } if "Association" in dict_addr: all_addresses.append( dict_addr["Association"]["PublicIp"]) dict_ret["ip"] = IP( dict_addr["Association"]["PublicIp"], int_mask=32) dict_ret["dns"] = dict_addr["Association"][ "PublicDnsName"] lst_ret.append(dict_ret) # Private dict_ret = { "sg_id": sec_grp["GroupId"], "sg_name": sec_grp["GroupName"], "description": description } all_addresses.append(dict_addr["PrivateIpAddress"]) dict_ret["ip"] = IP(dict_addr["PrivateIpAddress"], int_mask=32) if "PrivateDnsName" in dict_addr: dict_ret["dns"] = dict_addr["PrivateDnsName"] lst_ret.append(dict_ret) if self.private_ip_address.str_address not in all_addresses: raise Exception if self.dict_src["Ipv6Addresses"]: pdb.set_trace() for dict_addr in self.ipv6_addresses: pdb.set_trace() all_addresses.append(dict_addr["Association"]["PublicIp"]) all_addresses.append(dict_addr["PrivateIpAddress"]) if self.private_ip_address.str_address not in all_addresses: raise Exception return lst_ret
def get_all_leases(self): leases = [] for ip in IP([192, 168, 1, 1]).upto( IP([192, 168, 1, 20]) ): # for the sake of simplicity, we set the ip range statically (should be a config option) lease = db_session.query(DHCPLease).filter( DHCPLease.ip_str == str(ip)).first() if lease == None: # there is no lease currently, so we return a blank object with just the ip set leases.append(DHCPLease(ip_str=str(ip))) else: leases.append(lease) db_session.expunge_all( ) # detach the objects from the database session, so the user can not directly change the database return leases
def get_all_leases(self): valuedicts = [] for ip in IP([192, 168, 1, 1]).upto( IP([192, 168, 1, 20]) ): # for the sake of simplicity, we set the ip range statically (should be a config option) ip_str = str(ip) # is there any current reservation for that lease? records = self.ip_schedule.find(resource_id=ip_str, start_time=datetime.utcnow()) if not records: # empty list valuedicts.append(self._convert_reservation_to_dict(ip_str)) else: # there should only be one record valuedicts.append( self._convert_reservation_to_dict(ip_str, records[0])) return valuedicts
def get_suspicious(): recent_ip, recent_port = sniff_ip(TIME_TO_SNIFF) for ip_src in recent_ip: if not ip_src in IP_DICT.keys(): new_ip = IP(ip_src, TIME_TO_SNIFF) IP_DICT[ip_src] = new_ip IP_DICT[ip_src].add_count(recent_ip[ip_src]) for port_src in recent_port: if not port_src in PORT_DICT.keys(): new_port = Port(port_src, TIME_TO_SNIFF) PORT_DICT[port_src] = new_port PORT_DICT[port_src].add_count(recent_port[port_src]) for ip_src in IP_DICT: data = IP_DICT[ip_src].get_data() if data['velocity'] > SUSPICIOUS_VELOCITY or data[ 'acceleration'] > SUSPICIOUS_ACCELERATION: SUSPICIOUS_IPS.append(ip_src) for port_src in PORT_DICT: data = PORT_DICT[port_src].get_data() if data['velocity'] > SUSPICIOUS_VELOCITY or data[ 'acceleration'] > SUSPICIOUS_ACCELERATION: SUSPICIOUS_PORTS.append(port_src) return SUSPICIOUS_IPS, SUSPICIOUS_PORTS
def __init__(self, domain=None, ips=(), reverse_domains=(), strict=False): self.domain = None self.ips = [] # Type check - depends on what parameters have been passed if domain: self.type = 'domain' self.domain = domain self._get_ips() # Check if domain can be resolved only if strict flag is True if strict and not self.ips: # Couldn't resolve domain raise ValueError elif ips: self.type = 'ip' # IP raises ValueError if passed an invalid value self.ips = [IP(str(ip), reverse_domains) for ip in ips] else: raise ValueError self.mx = set() self.ns = set() self.whois_domain = None self.linkedin_page = None self.urls = {} self.related_hosts = set() self.subdomains = set() self.google_subdomains = set() self.cidrs = set()
def _get_ips(self): """ Does direct DNS lookup to get IPs from self.domains. Used internally by self.lookup_dns() """ if self.domain and not self.ips: ips = lookup.direct_dns(self.domain) if ips: self.ips = [IP(str(ip)) for ip in ips]
def clicked(self, window): ip = IP() #private ip private = Label(window, text="Private IP: " + ip.lan_ip) private.grid(column=1, row=3) #public ip private = Label(window, text="Public IP: " + ip.wan_ip) private.grid(column=1, row=4)
def test_basic(self): s = 'E\x00\x02\x08\xc15\x00\x00\x80\x11\x92aBk0\x01Bk0w\x005\xc07\x01\xf4\xda\xc2d\xd2\x81\x80\x00\x01\x00\x03\x00\x0b\x00\x0b\x03www\x06google\x03com\x00\x00\x01\x00\x01\xc0\x0c\x00\x05\x00\x01\x00\x00\x03V\x00\x17\x03www\x06google\x06akadns\x03net\x00\xc0,\x00\x01\x00\x01\x00\x00\x01\xa3\x00\x04@\xe9\xabh\xc0,\x00\x01\x00\x01\x00\x00\x01\xa3\x00\x04@\xe9\xabc\xc07\x00\x02\x00\x01\x00\x00KG\x00\x0c\x04usw5\x04akam\xc0>\xc07\x00\x02\x00\x01\x00\x00KG\x00\x07\x04usw6\xc0t\xc07\x00\x02\x00\x01\x00\x00KG\x00\x07\x04usw7\xc0t\xc07\x00\x02\x00\x01\x00\x00KG\x00\x08\x05asia3\xc0t\xc07\x00\x02\x00\x01\x00\x00KG\x00\x05\x02za\xc07\xc07\x00\x02\x00\x01\x00\x00KG\x00\x0f\x02zc\x06akadns\x03org\x00\xc07\x00\x02\x00\x01\x00\x00KG\x00\x05\x02zf\xc07\xc07\x00\x02\x00\x01\x00\x00KG\x00\x05\x02zh\xc0\xd5\xc07\x00\x02\x00\x01\x00\x00KG\x00\x07\x04eur3\xc0t\xc07\x00\x02\x00\x01\x00\x00KG\x00\x07\x04use2\xc0t\xc07\x00\x02\x00\x01\x00\x00KG\x00\x07\x04use4\xc0t\xc0\xc1\x00\x01\x00\x01\x00\x00\xfb4\x00\x04\xd0\xb9\x84\xb0\xc0\xd2\x00\x01\x00\x01\x00\x001\x0c\x00\x04?\xf1\xc76\xc0\xed\x00\x01\x00\x01\x00\x00\xfb4\x00\x04?\xd7\xc6S\xc0\xfe\x00\x01\x00\x01\x00\x001\x0c\x00\x04?\xd00.\xc1\x0f\x00\x01\x00\x01\x00\x00\n\xdf\x00\x04\xc1-\x01g\xc1"\x00\x01\x00\x01\x00\x00\x101\x00\x04?\xd1\xaa\x88\xc15\x00\x01\x00\x01\x00\x00\r\x1a\x00\x04PCC\xb6\xc0o\x00\x01\x00\x01\x00\x00\x10\x7f\x00\x04?\xf1I\xd6\xc0\x87\x00\x01\x00\x01\x00\x00\n\xdf\x00\x04\xce\x84dl\xc0\x9a\x00\x01\x00\x01\x00\x00\n\xdf\x00\x04A\xcb\xea\x1b\xc0\xad\x00\x01\x00\x01\x00\x00\x0b)\x00\x04\xc1l\x9a\t' ip = IP(s) dns = DNS(ip.udp.data) self.failUnless(dns.qd[0].name == 'www.google.com' and dns.an[1].name == 'www.google.akadns.net') s = '\x05\xf5\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x03cnn\x03com\x00\x00\x01\x00\x01' dns = DNS(s) self.failUnless(s == str(dns))
def init_ip_addresses(self, key_name, lst_src): for dict_src in lst_src: if "CidrIp" in dict_src: ip = IP(dict_src["CidrIp"]) elif "CidrIpv6" in dict_src: ip = IP(dict_src["CidrIpv6"]) else: raise NotImplementedError description = dict_src[ "Description"] if "Description" in dict_src else None addr = self.Address(ip, description=description) if addr.ip.type == IP.Types.IPV4: self.ipv4_ranges.append(addr) elif addr.ip.type == IP.Types.IPV6: self.ipv6_ranges.append(addr) else: raise NotImplemented
def get_ip_address(self): """ Get the associated IP address, if any or None otherwise. A ValueError is raised if the data is not a valid IP address. """ if self.data: return IP(self.data, ipversion=self.ip_version, make_net=self.network_only)
def add_epg_static(self, epg_dn, ep_net, next_hop): ep_net = IP(ep_net) if ep_net.mask is None: ep_net.mask = 32 next_hop = IP(next_hop) for ip in ep_net.ips_in_network: js = { "fvSubnet": { "attributes": { "ctrl": "no-default-gateway", "dn": f"{epg_dn}/subnet-[{ip}/32]", "ip": f"{ip}/32", "preferred": "no", "scope": "public,shared", "virtual": "no" }, "children": [ { "fvEpReachability": { "attributes": {}, "children": [ { "ipNexthopEpP": { "attributes": { "nhAddr": next_hop.ip } } } ] } } ] } } if self.post(js) != 200: raise Exception(f"Addition of EPG static Endpoint Route failed. {self.apic.response.text}") return True
def find_ips_from_dns(dns): print("todo: init address from dns: {}".format(dns)) ip = IP("1.1.1.1/32") return [ip] try: addr_info_lst = socket.getaddrinfo(dns, None) except socket.gaierror as e: raise Exception("Can't find address from socket") addresses = {addr_info[4][0] for addr_info in addr_info_lst} addresses = {IP(address, int_mask=32) for address in addresses} if len(addresses) != 1: pdb.set_trace() raise NotImplementedError for address in addresses: endpoint["ip"] = address print("todo: init address from dns: {}".format(dns)) ip = IP("1.1.1.1") return ip
def __init__(self, distant_host, local_host, probe_count, protocol, description, verbose): self.distant_host = distant_host self.local_host = local_host if local_host is not None else IP().ip self.protocol = protocol self.description = description self.verbose = verbose self.probe_count = probe_count whois = Whois(distant_host) ps = ProbeSelector(asn=whois.get_asn(), country_code=whois.get_country(), target=distant_host, probe_count=probe_count) self.probe_ids = [ str(x['prb_id']) for x in ps.get_near_probes_results() ] self.msm_id = None # set when msm is created
def ip(self, hit): ip = hit.get_ip() checker = IP() if ip: if checker.check_ip_is_tor(ip): msg = "User with TOR spotted" self.check.send_alert(msg, hit) return msg if checker.check_ip_virus_total(ip): msg = "User from malicious IP spotted" self.check.send_alert(msg, hit) return msg attack = self.check.check_attack_db(ip) if not isinstance(attack, bool): self.check.send_alert(attack, hit) return attack return True
def main(): """ main block """ if os.name == "nt": # Windows socket_protocol = socket.IPPROTO_IP else: # Internet Control Message Protocol socket_protocol = socket.IPPROTO_ICMP # Raw socket means you can determine every section of packet, either header or payload # Layer3 socket, Network Layer Protocol = IPv4 sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol) sniffer.bind((HOST, 0)) # we want the IP headers included in the capture # HDRINCL, when true, indicates the app provides the IP header. Only to SOCKET_RAW sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # if we're on Windows we need to send som ioctls # to setup promiscuous mode if os.name == "nt": # SIO_RCVALL control code enables a socket to receive all IPv4 or IPv6 packets # passing through a network interface sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) try: while True: # read in a single packet raw_buffer = sniffer.recvfrom(65565)[0] # create an IP header from the first 20 bytes of the buffer ip_header = IP(raw_buffer[0:20]) print "Protocol: %s %s -> %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address) except KeyboardInterrupt: # if we're on Windows turn off promiscuous mode if os.name == "nt": sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
def _receive_host(self, datagram): """ Handles the frame and sends the processed data to the host. """ self.received_datagrams += 1 if (hasattr(datagram, "dst_ip") and hasattr(datagram, "segment")): if self.ip_addr == datagram.dst_ip or datagram.dst_ip == IP( ): # or in broadcast self.lgr.log( simpynet.__NETWORK_LOG_N__, " " + str(float(self.env.now)) + " " + repr(self.ip_addr) + ' : Received from: ' + repr(datagram.src_ip)) for h in self.transport_handler: h(datagram.segment) else: self.lgr.log( simpynet.__NETWORK_LOG_N__, " " + str(float(self.env.now)) + " " + repr(self.ip_addr) + ' : Discarded from: ' + repr(datagram.src_ip)) self.discarded_datagrams += 1 else: self.corrupted_datagrams += 1
def new_req(self, tid): md = self.__req_method(self.method) cd = self.__req_status(self.status) tp = self.__req_type(self.url) oIP = IP(self.db, self.ip) self.db.table("t_requests").insert(tid=tid, line=self.line, ip=self.ip, ipcount=1, country=oIP.ipinfo['country'], city=oIP.ipinfo['city'], get=md['get'], post=md['post'], put=md['put'], head=md['head'], connect=md['connect'], unknow=md['unknow'], status_200=cd['status_200'], status_206=cd['status_206'], status_302=cd['status_302'], status_304=cd['status_304'], status_400=cd['status_400'], status_403=cd['status_403'], status_404=cd['status_404'], status_500=cd['status_500'], status_502=cd['status_502'], status_503=cd['status_503'], status_unknow=cd['status_unknow'], flow_byte=self.bytes, url_app=tp['url_app'], url_static=tp['url_static'], url_video=tp['url_video'], url_zip=tp['url_zip'], url_doc=tp['url_doc'], url_other=tp['url_other']) self.db.execute(None, False)
from ip import IP import time start_time = time.time() angles = [0, 15, 30, 45, 60] #vinkler for i in range(len(angles)): c = IP(Ncol=344, Nrow=260, theta=angles[i]) c.invasion() print("--- %s seconds ---" % (time.time() - start_time))
def run(distant_host, local_host, protocol, probe_count, description, compact, verbose): if verbose: logging.info( 'running Paris-traceroute towards {}.'.format(distant_host)) logging.info('Inferred local IP: {}.'.format(IP().ip)) forward_traceroute = ParisTraceroute(distant_host, protocol=protocol) forward_traceroute.start() if protocol.lower() != 'icmp': forward_icmp_traceroute = ParisTraceroute(distant_host, protocol='ICMP') forward_icmp_traceroute.start() rt = ReverseTraceroute(distant_host=distant_host, local_host=local_host, probe_count=probe_count, protocol=protocol, description=description, verbose=verbose) results = rt.run() forward_traceroute.join() if protocol.lower() != 'icmp': forward_icmp_traceroute.join() if not compact: print("Forward path:") if forward_traceroute.errors: if verbose: logging.info('Don\'t have root proviledges for paris-traceroute, ' 'using mtr instead. Consider running with sudo.') forward_traceroute = Mtr(distant_host) forward_traceroute.start() forward_traceroute.join() parsed_ft_results = MtrRenderer.parse(forward_traceroute.output) if not compact: MtrRenderer.render(parsed_ft_results) else: parsed_ft_results = ParisTracerouteRenderer.parse( forward_traceroute.output) if protocol.lower() != 'icmp': parsed_ft_icmp_results = ParisTracerouteRenderer.parse( forward_icmp_traceroute.output) # if end of paths contains unknown host (*), try # to complete the path to the destination using icmp parsed_ft_results = PathComparator.merge_paths( parsed_ft_results, parsed_ft_icmp_results) if not compact: ParisTracerouteRenderer.render(parsed_ft_results) if not compact: print("Return path:") parsed_rt_results = TracerouteRenderer.parse(results) if not compact: TracerouteRenderer.render(parsed_rt_results) # print ASN Paths path_comparator = PathComparator(parsed_ft_results, parsed_rt_results) path_comparator.print_asn_paths() asn_symmetrical = path_comparator.compare_paths_by_asns() if asn_symmetrical: print('\n{}ASN paths appear to be symmetrical.{}'.format( ConsoleColors.OKGREEN, ConsoleColors.ENDC)) else: print('\n{}ASN paths appear NOT to be symmetrical.{}'.format( ConsoleColors.WARNING, ConsoleColors.ENDC)) # print Hostname paths path_comparator.print_hostname_paths() hostname_symmetrical = path_comparator.compare_paths_by_hostnames() if hostname_symmetrical: print('\n{}Hostname paths appear to be symmetrical.{}'.format( ConsoleColors.OKGREEN, ConsoleColors.ENDC)) else: print('\n{}Hostname paths appear NOT to be symmetrical.{}'.format( ConsoleColors.WARNING, ConsoleColors.ENDC)) ft_individual_paths = path_comparator.extract_individual_paths( parsed_ft_results) gv = GraphVisualizer(ft_individual_paths) gv.create_nxgraph() gv.highlight_return_path(return_path=parsed_rt_results) gv.save(name=distant_host)
def _init_private_ip_address(self, _, value): self.private_ip_address = IP(value + "/32")
def _init_private_ip_address_from_cache(self, _, value): if self.private_ip_address is not None: raise NotImplementedError else: self.private_ip_address = IP(value, from_dict=True)
self.callback = None self.fila = [] def registrar_recebedor(self, callback): self.callback = callback def enviar(self, datagrama, next_hop): self.fila.append((datagrama, next_hop)) def rand_ip(): return '%d.%d.%d.%d' % tuple(random.randint(1, 255) for i in range(4)) enlace = CamadaEnlace() rede = IP(enlace) def enviar_datagrama(dest): datagrama = b'E\x00\x00\x14\x00\x00\x00\x00@\x06\x00\x00\x01\x02\x03\x04' + str2addr( dest) assert len(datagrama) == 20 enlace.callback(datagrama[:-10] + struct.pack('!H', calc_checksum(datagrama)) + datagrama[-8:]) assert len( enlace.fila ) == 1, 'Só foi recebido um datagrama, mas foi encaminhado mais de um' datagrama, next_hop = enlace.fila.pop() assert len(datagrama) == 20, 'O tamanho mudou ao ser encaminhado' dscp, ecn, identification, flags, frag_offset, ttl, proto, \
print(message) # print(f' - - ) @staticmethod def print_and_exit(message: str, code: int = 1): logger.critical(message) sys.exit(code) if __name__ == '__main__': args = create_arg_parser() global logger logger = get_logger(args.verbose, 'openvas') openvas: OpenVas = OpenVas(IP(args.host), args.user, args.password) if args.target: ip = IP(args.target) openvas.analize_ip(ip, args.type) elif args.format and args.id: # report_id = '9331a947-2a02-4979-8933-ddea8bb2bbd7' openvas.report(args.id, args.format) elif args.list: openvas.list_tasks() else: logger.info("Argument necesary") sys.exit(0) # pdf_report_format_id = "1a60a67e-97d0-4cbf-bc77-f71b08e7043d"
def __init__(self, ip, description=None, from_cache=False): super(EC2SecurityGroup.IpPermission.Address, self).__init__({}) if from_cache is True: ip = IP(ip, from_dict=True) self.ip = ip self.description = description
#!/usr/bin/env python3 # Antes de usar, execute o seguinte comando para evitar que o Linux feche # as conexões TCP que o seu programa estiver tratando: # # sudo iptables -I OUTPUT -p tcp --tcp-flags RST RST -j DROP # Este é um exemplo de um programa que faz eco, ou seja, envia de volta para # o cliente tudo que for recebido em uma conexão. import asyncio from ip import IP from tcp import Servidor def dados_recebidos(conexao, dados): if dados == b'': conexao.fechar() else: conexao.enviar(dados) # envia de volta def conexao_aceita(conexao): conexao.registrar_recebedor( dados_recebidos) # usa esse mesmo recebedor para toda conexão aceita rede = IP() servidor = Servidor(rede, 7000) servidor.registrar_monitor_de_conexoes_aceitas(conexao_aceita) asyncio.get_event_loop().run_forever()
def ConsultaIP(message): bot.reply_to(message, IP(message))
def ip(self, address): if isinstance(address, IP): self.__ip = address else: self.__ip = IP(address)
f'--script "default or (discovery and safe)" -oX "{ip.ip}_advanced.xml" {ip.ip} > ' \ f'"{ip.ip}_advanced.txt"' logging.info(command) stdout, stderr, execute = execute_command(command) if len(stderr) > 0: logging.error(stderr) logging.debug(f"Thread nmap advanced: finishing") if __name__ == "__main__": format = "%(asctime)s: %(message)s" logging.basicConfig(format=format, level=logging.DEBUG, datefmt="%H:%M:%S") arg: argparse = create_arg_parser() print(arg) ip: IP = IP(arg.ip) logging.info("Main : before creating thread") simple = threading.Thread(target=thread_nmap_simple, args=(ip, )) simple.start() if arg.advanced: advanced = threading.Thread(target=thread_nmap_advanced, args=(ip, )) advanced.start() logging.info("Main : wait for the threads to finished") simple.join() if arg.advanced: advanced.join() logging.info("Main : all done")