예제 #1
0
    def informationURL(self):
        logging.info('Se ha inicializado la opcion WHOIS URL')
        url = input("Introduzca la URL a analizar:")
        res = ""
        if str(url) != "None":
            if url == "":
                res = res + "Has introducido una url vacia"
                logging.info('WHOIS URL: Se ha introducido una URL vacía')
                print("Has introducido una url vacia")
            else:
                # Para calcular la direccion IP de la URL introducida utilizamos la funcion socket.gethostbyname()
                #print (socket.gethostbyname(url))

                # Debemos controlar la excepción de que el usuario introduzca una URL errónea de modo que la aplicación devolvería error
                # (Si introduce una dirección IP no hay problema ya que la resuelve como ella misma)
                try:
                    ip = socket.gethostbyname(url)
                    #print(ip)
                    dirIP = IPWhois(ip)
                    #IMPORTANTE: CON LA VERSION QUE TIENE POR DEFECTO DABA WARNINGS, SIN EMBARGO HE INSTALADO LA SIGUIENTE VERSION CON EL SIGUIENTE COMANDO:
                    # py -m pip install ipwhois==0.10.3
                    logging.info('Se ha analizado la dirección: ' + url +
                                 ' con direccion IP: ' + ip)
                    result = dirIP.lookup_rws()
                    res = res + "\nINFORMACIÓN SOBRE EL DOMINIO: " + url
                    res = res + "\n\nASN: " + result['asn']
                    res = res + "\nASN_CIDR: " + result['asn_cidr']
                    res = res + "\nASN_COUNTRY_CODE: " + result[
                        'asn_country_code']
                    res = res + "\nASN_DATE: " + result['asn_date']
                    res = res + "\nASN_REGISTRY: " + result['asn_registry']

                    res = res + "\n\nAbuse emails: " + str(
                        result['nets'][0]['abuse_emails'])
                    res = res + "\nAddress: " + str(
                        result['nets'][0]['address'])
                    res = res + "\nCidr: " + str(result['nets'][0]['cidr'])
                    res = res + "\nCity: " + str(result['nets'][0]['city'])
                    res = res + "\nCountry: " + str(
                        result['nets'][0]['country'])
                    res = res + "\nCreated: " + str(
                        result['nets'][0]['created'])
                    res = res + "\nDescription: " + str(
                        result['nets'][0]['description'])
                    res = res + "\nMisc Emails: " + str(
                        result['nets'][0]['misc_emails'])
                    res = res + "\nName: " + str(result['nets'][0]['name'])
                    res = res + "\nPostal Code: " + str(
                        result['nets'][0]['postal_code'])
                    res = res + "\nState: " + str(result['nets'][0]['state'])
                    res = res + "\nTech emails: " + str(
                        result['nets'][0]['tech_emails'])
                    res = res + "\nUpdated: " + str(
                        result['nets'][0]['updated'])

                    print(res)

                except ValueError:
                    messagebox.showerror("ERROR",
                                         "La URL: " + url + " no es correcta")
예제 #2
0
    def test_lookup_rws(self):
        try:
            from urllib.request import ProxyHandler, build_opener
        except ImportError:
            from urllib2 import ProxyHandler, build_opener

        ips = [
            '74.125.225.229',  # ARIN
            '2001:4860:4860::8888',
            '62.239.237.1',  # RIPE
            '2a00:2381:ffff::1',
            '210.107.73.73',  # APNIC
            '2001:240:10c:1::ca20:9d1d',
            '200.57.141.161',  # LACNIC
            '2801:10:c000::',
            '196.11.240.215',  # AFRINIC
            '2001:43f8:7b0::'
        ]

        for ip in ips:

            result = IPWhois(ip)
            try:
                self.assertIsInstance(result.lookup_rws(), dict)
            except (ASNLookupError, ASNRegistryError, WhoisLookupError):
                pass
            except AssertionError as e:
                raise e
            except Exception as e:
                self.fail('Unexpected exception raised: %r' % e)

        handler = ProxyHandler({'http': 'http://0.0.0.0:80/'})
        opener = build_opener(handler)
        result = IPWhois('74.125.225.229', 0, opener)
        self.assertRaises(WhoisLookupError, result.lookup_rws)
예제 #3
0
    def test_lookup_rws(self):
        try:
            from urllib.request import ProxyHandler, build_opener
        except ImportError:
            from urllib2 import ProxyHandler, build_opener

        ips = [
            '74.125.225.229',  # ARIN
            '2001:4860:4860::8888',
            '62.239.237.1',  # RIPE
            '2a00:2381:ffff::1',
            '210.107.73.73',  # APNIC
            '2001:240:10c:1::ca20:9d1d',
            '200.57.141.161',  # LACNIC
            '2801:10:c000::',
            '196.11.240.215',  # AFRINIC
            '2001:43f8:7b0::'
        ]

        for ip in ips:

            result = IPWhois(ip)
            try:
                self.assertIsInstance(result.lookup_rws(), dict)
            except (ASNLookupError, ASNRegistryError, WhoisLookupError):
                pass
            except AssertionError as e:
                raise e
            except Exception as e:
                self.fail('Unexpected exception raised: %r' % e)

        handler = ProxyHandler({'http': 'http://0.0.0.0:80/'})
        opener = build_opener(handler)
        result = IPWhois('74.125.225.229', 0, opener)
        self.assertRaises(WhoisLookupError, result.lookup_rws)
예제 #4
0
def ipWhois():
    # Call backup_myIPwhois.py
    # myIPwhois.IPWhoisChecker("https://www.abuseipdb.com/whois/" + sys.argv[1])

    # IPWhois (pip3 install ipwhois == 0.10.3)
    ipwhoisInfo = IPWhois(sys.argv[1])
    ipwhoisResults = ipwhoisInfo.lookup_rws()
    pprint(ipwhoisResults)
예제 #5
0
    def gather(self, all_ips):

        for path, incoming_ip_obj in all_ips.iteritems():

            if incoming_ip_obj[0].ip_whois == "":

                try:
                    print "Gathering whois information about " + incoming_ip_obj[0].ip_address
                    ip_whois = IPWhois(incoming_ip_obj[0].ip_address)
                    incoming_ip_obj[0].ip_whois = ip_whois.lookup_rws()
                except IPDefinedError:
                    print helpers.color("[*] Error: Private IP address, skipping IP!", warning=True)
        return
예제 #6
0
 def test_lookup_rws(self):
     from urllib import request
     result = IPWhois('74.125.225.229')
     try:
         self.assertIsInstance(result.lookup_rws(), dict)
     except (ASNLookupError, WhoisLookupError):
         pass
     except AssertionError as e:
         raise e
     except Exception as e:
         self.fail('Unexpected exception raised: %r' % e)
     handler = request.ProxyHandler({'http': 'http://0.0.0.0:80/'})
     opener = request.build_opener(handler)
     result = IPWhois('74.125.225.229', 0, opener)
     self.assertRaises(WhoisLookupError, result.lookup_rws)
예제 #7
0
 def execute(self):
     addr = self.target
     obj = IPWhois(addr)
     self.result = obj.lookup_rws()
     print self.result
	def whois():
	
			obj = IPWhois(ip)
			results = obj.lookup_rws()
			pprint.pprint(results)
def notify_service(intervallo, ip, labels, kind, u="", p=""):

    blck = os.path.join(os.path.join(os.environ['USERPROFILE']),
                        'Documents') + "\\smersh_blacklist.txt"
    mail_setting = os.path.join(os.path.join(os.environ['USERPROFILE']),
                                'Documents') + "\\smersh_mail_setting.txt"
    keywords = os.path.join(os.path.join(os.environ['USERPROFILE']),
                            'Documents') + "\\smersh_extractor_keywords.txt"

    with open(keywords, mode="r") as file:
        config_file = file.read().splitlines()

    done = False
    while not done:
        try:
            with open(mail_setting, mode="r") as file:
                content = file.read().split("|")
            done = True
        except:
            # Il file potrebbe essere usato contemporaneamente da smersh-on poller e blacklist poller se runnati
            # contemporaneamente. Pertanto ho previsto questa eccezione.
            time.sleep(3)

    now = datetime.now()
    timestamp = now.strftime("%d/%m/%Y %H:%M:%S")

    if not labels:
        fatto = False
        while not fatto:
            try:
                with open(blck, mode='r') as file:
                    listato = file.read().splitlines()
                fatto = True
            except:
                # Il file potrebbe essere usato contemporaneamente da smersh-on poller e blacklist poller se runnati
                # contemporaneamente. Pertanto ho previsto questa eccezione.
                time.sleep(3)

        for add in ip:
            for idx, x in enumerate(listato):
                if add in x:
                    labels.append(listato[idx - 1])
                    break
                elif idx + 1 == len(listato):
                    # Mi ricavo il net name tramite whois:
                    from ipwhois import IPWhois
                    import urllib2

                    handler = urllib2.ProxyHandler({
                        'http':
                        'http://' + u + ':' + p + '@' + config_file[11]
                    })
                    try:
                        opener = urllib2.build_opener(handler)
                        obj = IPWhois(add, proxy_opener=opener)
                        results = obj.lookup_rws()

                        netname = results["nets"][0]["name"]
                    except:
                        netname = "## INDIRIZZO NON RISOLTO!"

                    labels.append("# " + netname)
                    #labels.append("NUOVO IP")

                    # Quindi aggiungiamoli alla blacklist se dopo averla scorsa tutta non trovo corrispondenze
                    #label = "# NUOVO - DA VERIFICARE"

                    try:
                        with open(blck, mode="a") as blacklist:
                            blacklist.write("\n# " + netname)
                            blacklist.write("\n" + add)
                            print "\n[*] Blacklist file aggiornata con successo!"
                    except:
                        print u"\n[!] Qualcosa è andato storto nell'aggiornamento della blacklist!"
                        traceback.print_stack()

    for add in ip:
        # Infine estraiamo i dati generati dagli IP Segnalati...
        try:
            from smersh_off_forensics import estrattore_dati

            with open(blck, "r") as file:
                listone = file.read().splitlines()

            dest = [
                listone[idx - 1] for idx, x in enumerate(listone) if add in x
            ]
            dest = dest[0].replace("#", "").replace(" ", "")
            folder_estrazione = os.path.join(
                os.path.join(os.environ['USERPROFILE']),
                'Desktop') + "\\Estrazioni_Elaborate\\" + dest

            if not os.path.exists(folder_estrazione):
                os.makedirs(folder_estrazione)

            estrattore_dati(choose="5",
                            ips=add,
                            intervallo=(86400),
                            verbose=False,
                            save_path=folder_estrazione)

            print "\n[*] Estrazioni report avvenuta con successo!"
        except:
            print u"\n[!] Qualcosa è andato storto con il dump delle attività degli IP segnalati."
            traceback.print_stack()
            return None

    sender = content[0]
    receivers = content[1].split(',')
    message_payload = content[2].format(kind, str(intervallo), ", ".join(ip),
                                        ", ".join(labels), timestamp)
    address = content[3]

    try:
        smtpObj = smtplib.SMTP(address)
        smtpObj.sendmail(sender, receivers, message_payload)
        print "\n   [***] Notificate figure interessate!"
    except smtplib.SMTPException:
        print "\n[!] Error: unable to send email"

    return None