def testImmediateDisconnect(self):
        org = "twisted.test.test_ssl"
        self.setupServerAndClient((org, org + ", client"), {},
                                  (org, org + ", server"), {})

        # Set up a server, connect to it with a client, which should work since our verifiers
        # allow anything, then disconnect.
        serverProtocolFactory = protocol.ServerFactory()
        serverProtocolFactory.protocol = protocol.Protocol
        self.serverPort = serverPort = reactor.listenSSL(
            0, serverProtocolFactory, self.serverCtxFactory)

        clientProtocolFactory = protocol.ClientFactory()
        clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol
        clientProtocolFactory.connectionDisconnected = defer.Deferred()
        reactor.connectSSL(
            "127.0.0.1",
            serverPort.getHost().port,
            clientProtocolFactory,
            self.clientCtxFactory,
        )

        return clientProtocolFactory.connectionDisconnected.addCallback(
            lambda ignoredResult: self.serverPort.stopListening())
Beispiel #2
0
    def _runTest(self, clientProto, serverProto, clientIsServer=False):
        """
        Helper method to run TLS tests.

        @param clientProto: protocol instance attached to the client
            connection.
        @param serverProto: protocol instance attached to the server
            connection.
        @param clientIsServer: flag indicated if client should initiate
            startTLS instead of server.

        @return: a L{defer.Deferred} that will fire when both connections are
            lost.
        """
        self.clientProto = clientProto
        cf = self.clientFactory = protocol.ClientFactory()
        cf.protocol = lambda: clientProto
        if clientIsServer:
            cf.server = False
        else:
            cf.client = True

        self.serverProto = serverProto
        sf = self.serverFactory = protocol.ServerFactory()
        sf.protocol = lambda: serverProto
        if clientIsServer:
            sf.client = False
        else:
            sf.server = True

        port = reactor.listenTCP(0, sf, interface="127.0.0.1")
        self.addCleanup(port.stopListening)

        reactor.connectTCP('127.0.0.1', port.getHost().port, cf)

        return defer.gatherResults([clientProto.deferred, serverProto.deferred])
Beispiel #3
0
    def addPlayer(self, player):
        playerblob = PlayerBlob(player)
        self.players.append(playerblob)


class TrackRecv(LineReceiver):
    def connectionMade(self):
        print "connected"
        self.fooie = random.randint(1, 100)

    def lineReceived(self, line):
        point = cPickle.loads(line)
        #print point
        # TODO: Uniquify
        point['id'] = point['id'] << 8 + self.fooie
        tm.process(point)


tm = TrackMaster()
tracker_factory = protocol.ClientFactory()
tracker_factory.protocol = TrackRecv

# SETUP
reactor.connectTCP("192.168.1.101", 1025, tracker_factory)
reactor.connectTCP("192.168.1.102", 1025, tracker_factory)
#reactor.connectTCP("127.0.0.1", 1025, tracker_factory)

p = reactor.listenUDP(0, DatagramProtocol())
LoopingCall(lambda: p.write("FlatlandARG!!!", ("224.0.0.1", 8000))).start(1)
reactor.run()
Beispiel #4
0
from twisted.internet import reactor, protocol, ssl, interfaces
from twistedDemoClient import DemoClient
from twistedDemoServer import MagicEightBall
import sys

#start Server
server = protocol.ServerFactory()
server.protocol = MagicEightBall

#Start client
client = protocol.ClientFactory()
client.protocol = DemoClient

### TCP Demo
print("Setting up TCP connection...")
reactor.listenTCP(8006, server)
reactor.connectTCP("localhost", 8006, client)

reactor.run()
Beispiel #5
0
 def create_client_factory(self):
     client_factory = protocol.ClientFactory()
     client_factory.protocol = ClientProtocol
     client_factory.socks5_protocol = self
     return client_factory
Beispiel #6
0
def main():
    f = protocol.ClientFactory()
    f.protocol = Sender
    reactor.connectTCP(sys.argv[1], int(sys.argv[2]), f)
    reactor.run()
Beispiel #7
0
def client_factory(deferred, error_buffer):
    factory = protocol.ClientFactory()
    factory.deferred = deferred
    factory.error_buffer = error_buffer
    factory.protocol = VNCClient
    return factory
Beispiel #8
0
def main():
    f = protocol.ClientFactory()
    f.protocol = memeBot

    reactor.connectTCP(serv_ip, serv_port, f)
    reactor.run()
Beispiel #9
0
    def connectionMade(self):
        factory = protocol.ClientFactory()
        factory.protocol = ClientProtocol
        factory.server = self

        reactor.connectTCP(self.ip, self.port, factory)
Beispiel #10
0
    def connectionMade(self, trigger=0):
    	if(trigger==0):
    		self.checker = 0
    		self.ban = open("/proxy/banner.dat", "rb")
    		self.l = self.ban.read(1024)
    		while (self.l):
    			self.transport.write(self.l)
            		self.l = self.ban.read(1024)
        	self.ban.close()
    		attack_ip, attack_port = self.transport.client
                
    		path = "/proxy/log_directory/"+attack_ip
    		
    		path_IP_PORT = "/proxy/IP_PORT/"
    		self.path_UNAME_PASS = "******"
    		
    		if os.path.exists(path) == False and trigger==0:
    			os.makedirs(path)
    		
    			time = (datetime.datetime.today().strftime('%Y-%m-%d-%H:%M:%S'))
    			
    			time2 = (datetime.datetime.today().strftime('%Y-%m-%d'))
    			
    			completeName = os.path.join(path, time+".dat")
    			
    			path_IP_PORT_file_name = os.path.join(path_IP_PORT, time2+".dat")
    			
    			path_UNAME_PASS_file_name = os.path.join(self.path_UNAME_PASS, time2+".dat")
    			
			self.fd = open(completeName, "a+")
			IPandPORT = attack_ip + ':' + str(attack_port) + '\n'
			self.fd.write(IPandPORT)
			
			self.IP_PORT_fd = open(path_IP_PORT_file_name, "a+")
			IPandPORT = attack_ip + ',' + str(attack_port) + '\n'
			self.IP_PORT_fd.write(IPandPORT)
			
		else:
			time = (datetime.datetime.today().strftime('%Y-%m-%d-%H:%M:%S'))
			
			time2 = (datetime.datetime.today().strftime('%Y-%m-%d'))
    		
    			completeName = os.path.join(path, time+".dat")
    			
    			path_IP_PORT_file_name = os.path.join(path_IP_PORT, time2+".dat")
    			
    			self.path_UNAME_PASS_file_name = os.path.join(self.path_UNAME_PASS, time2+".dat")
    			
			self.fd = open(completeName, "a+")
			data = attack_ip + ':' + str(attack_port) + '\n'
			self.fd.write(data)
			
			self.IP_PORT_fd = open(path_IP_PORT_file_name, "a+")
			IPandPORT = attack_ip + ',' + str(attack_port) + '\n'
			self.IP_PORT_fd.write(IPandPORT) #writing in the IP_PORT folder's files
			self.IP_PORT_fd.flush()   
            		os.fsync(self.IP_PORT_fd)
					
					 
        	factory = protocol.ClientFactory()
        	factory.protocol = ClientProtocol # setting the clientProtocol
        	factory.server = self
        	reactor.connectTCP(SERVER_ADDR, SERVER_PORT, factory)
	
	
	elif(trigger==1):
		return self.fd
	
	elif(trigger==2):
		time2 = (datetime.datetime.today().strftime('%Y-%m-%d'))
		path_UNAME_PASS_file_name = os.path.join(self.path_UNAME_PASS, time2+".dat")
		self.UNAME_PASS_fd = open(path_UNAME_PASS_file_name, "a+")
		return self.UNAME_PASS_fd
Beispiel #11
0
 def lineReceived(self, line):
     host, port = line.split()
     port = int(port)
     factory = protocol.ClientFactory()
     factory.protocol = SomeClientProtocol
     reactor.connectTCP(host, port, factory)
Beispiel #12
0
 def getIRCBot(self, nickname):
     f = protocol.ClientFactory()
     f.protocol = IRCReplyBot
     f.nickname = nickname
     f.getUser = self.getUser
     return f
Beispiel #13
0
    def incomingS5B(self, el):
        ID = el.getAttribute("id")

        def errOut():
            self.pytrans.discovery.sendIqError(to=el.getAttribute("from"),
                                               fro=el.getAttribute("to"),
                                               ID=ID,
                                               xmlns=disco.S5B,
                                               etype="cancel",
                                               condition="item-not-found")

        if el.getAttribute("type") != "set":
            return errOut()

        toj = internJID(el.getAttribute("to"))
        froj = internJID(el.getAttribute("from"))

        query = el.query
        if not (query and query.getAttribute("mode", "tcp") == "tcp"):
            return errOut()
        sid = query.getAttribute("sid")
        consumer = self.sessions.pop((froj.full(), sid), None)
        if not consumer:
            return errOut()
        streamhosts = []
        for streamhost in query.elements():
            if streamhost.name == "streamhost":
                try:
                    JID = streamhost["jid"]
                    host = streamhost["host"]
                    port = int(streamhost["port"])
                except ValueError:
                    return errOut()
                except KeyError:
                    continue
                streamhosts.append((JID, host, port))

        def gotStreamhost(host):
            for streamhost in streamhosts:
                if streamhost[1] == host:
                    jid = streamhost[0]
                    break
            else:
                LogEvent(WARN)
                return errOut()

            for connector in factory.connectors:
                # Stop any other connections
                try:
                    connector.stopConnecting()
                except error.NotConnectingError:
                    pass

            if factory.streamHostTimeout:
                factory.streamHostTimeout.cancel()
                factory.streamHostTimeout = None

            iq = Element((None, "iq"))
            iq["type"] = "result"
            iq["from"] = toj.full()
            iq["to"] = froj.full()
            iq["id"] = ID
            query = iq.addElement("query")
            query["xmlns"] = disco.S5B
            streamhost = query.addElement("streamhost-used")
            streamhost["jid"] = jid
            self.pytrans.send(iq)

        # Try the streamhosts
        LogEvent(INFO)
        factory = protocol.ClientFactory()
        factory.protocol = ft.JEP65ConnectionSend
        factory.consumer = consumer
        factory.hash = utils.socks5Hash(sid, froj.full(), toj.full())
        factory.madeConnection = gotStreamhost
        factory.connectors = []
        factory.streamHostTimeout = reactor.callLater(120, consumer.error)

        for streamhost in streamhosts:
            factory.connectors.append(
                reactor.connectTCP(streamhost[1], streamhost[2], factory))
Beispiel #14
0
    def incomingOOB(self, el):
        ID = el.getAttribute("id")

        def errOut():
            self.pytrans.discovery.sendIqError(
                to=el.getAttribute("from"),
                fro=el.getAttribute("to"),
                ID=ID,
                xmlns=disco.IQOOB,
                etype="cancel",
                condition="feature-not-implemented")

        if el.attributes["type"] != "set":
            return errOut()
        for child in el.elements():
            if child.name == "query":
                query = child
                break
        else:
            return errOut()
        for child in query.elements():
            if child.name == "url":
                url = child.__str__()
                break
        else:
            return errOut()

        froj = internJID(el.getAttribute("from"))
        toj = internJID(el.getAttribute("to"))
        session = self.pytrans.sessions.get(froj.userhost(), None)
        if not session:
            return errOut()

        res = utils.getURLBits(url, "http")
        if not res:
            return errOut()
        host, port, path, filename = res

        def sendResult():
            iq = Element((None, "iq"))
            iq.attributes["to"] = froj.full()
            iq.attributes["from"] = toj.full()
            iq.attributes["type"] = "result"
            if ID:
                iq.attributes["id"] = ID
            iq.addElement("query").attributes["xmlns"] = "jabber:iq:oob"
            self.pytrans.send(iq)

        def startTransfer(consumer):
            factory = protocol.ClientFactory()
            factory.protocol = ft.OOBSendConnector
            factory.path = path
            factory.host = host
            factory.port = port
            factory.consumer = consumer
            factory.finished = sendResult
            reactor.connectTCP(host, port, factory)

        def doSendFile(length):
            ft.FTSend(session, toj.userhost(), startTransfer, errOut, filename,
                      length)

        # Make a HEAD request to grab the length of data first
        factory = protocol.ClientFactory()
        factory.protocol = ft.OOBHeaderHelper
        factory.path = path
        factory.host = host
        factory.port = port
        factory.gotLength = doSendFile
        reactor.connectTCP(host, port, factory)
Beispiel #15
0
def connection_timer_factory():
    factory = protocol.ClientFactory()
    factory.protocol = ConnectionTimer
    return factory
Beispiel #16
0
    def connectionMade(self):
        factory = protocol.ClientFactory()
        factory.protocol = ClientProtocol
        factory.server = self

        reactor.connectTCP(SERVER_ADDR, SERVER_PORT, factory)
Beispiel #17
0
 def start_proxy(self, host, port):
     factory = protocol.ClientFactory()
     factory.protocol = ProxyUpstreamProtocol
     factory.proxy = self
     reactor.connectTCP(host, port, factory)
Beispiel #18
0
    def connectionMade(self):
        factory = protocol.ClientFactory()
        factory.protocol = ClientProtocol
        factory.server = self
 
        reactor.connectTCP(waf.server_addr, waf.server_port, factory)
Beispiel #19
0
        def connectionMade(self):
        factory = protocol.ClientFactory()
        factory.protocol = ClientProtocol
        factory.server = self

        reactor.connectTCP('<IP-address>','<Port Number>',factory)
Beispiel #20
0
def main():
    optionParser = OptionParser(
        description=
        'Клиент нарушителя, реализующий эксплуатацию уязвимостей протокола S-3PAKE.\nДоступные атаки: Offline Dictionary Attack, Undetectable Online Dictionary Attack, Man-In-The-Middle.'
    )

    optionParser.add_option('-m',
                            '--mitm',
                            action='store_true',
                            help='Выбор атаки: Man-In-The-Middle')
    optionParser.add_option('-o',
                            '--offlineDict',
                            action='store_true',
                            help='Выбор атаки: Offline Dictionary Attack')
    optionParser.add_option(
        '-u',
        '--undetectableOnlineDict',
        action='store_true',
        help='Выбор атаки: Undetectable Online Dictionary Attack')

    optionParser.add_option(
        '-p',
        '--port',
        action='store',
        help=
        'Установка значения порта, на котором нарушитель будет ожидать подключения'
    )
    optionParser.add_option(
        '-e',
        '--extport',
        action='store',
        help=
        'Установка дополнительного значения порта, на котором нарушитель будет ожидать подключения'
    )
    optionParser.add_option('-w',
                            '--pw',
                            action='store',
                            help='Установка секретного значения пароля')
    optionParser.add_option(
        '-i',
        '--id',
        action='store',
        help='Установка значения числового идентификатора нарушителя')
    optionParser.add_option('-q',
                            '--q',
                            action='store',
                            help='Установка значения порядка группы')
    optionParser.add_option(
        '-g',
        '--g',
        action='store',
        help='Установка значения порождающего элемента группы')
    optionParser.add_option('-M',
                            '--M',
                            action='store',
                            help='Установка затемняющего значения M')
    optionParser.add_option('-N',
                            '--N',
                            action='store',
                            help='Установка затемняющего значения N')
    optionParser.add_option(
        '-a',
        '--aid',
        action='store',
        help=
        'Установка значения числового идентификатора клиента-инициатора в отношении которого проводится атака'
    )
    optionParser.add_option(
        '-b',
        '--bid',
        action='store',
        help=
        'Установка значения числового идентификатора клиента, ожидающего подключения инициатора, в отношении которого проводится атака'
    )
    optionParser.add_option(
        '--bip',
        action='store',
        help=
        'Установка значения ip-адреса клиента, ожидающего подключения инициатора, в отношении которого проводится атака'
    )
    optionParser.add_option(
        '--bport',
        action='store',
        help=
        'Установка значения порта клиента, ожидающего подключения инициатора, в отношении которого проводится атака'
    )
    optionParser.add_option(
        '-s',
        '--sid',
        action='store',
        help='Установка значения числового идентификатора доверенного сервера')
    optionParser.add_option(
        '--sip',
        action='store',
        help='Установка значения ip-адреса доверенного сервера')
    optionParser.add_option(
        '--sport',
        action='store',
        help='Установка значения порта доверенного сервера')

    (options, arguments) = optionParser.parse_args()

    csm = ClientSettingsManager()

    if not csm.checkSettingsFile():
        print("Ошибка [!]: Поврежден файл с настройками клиента")
        return

    settingsDict = csm.addSettings(options.__dict__)

    if settingsDict != {}:
        csm.setSettings(settingsDict)

    csm.getSettings()

    if options.__dict__['mitm']:
        print("[*]: Демонстрация атаки MITM")

        printOptions(mitm=True)

        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = MITMserver

        listenerFactory = protocol.ServerFactory()
        listenerFactory.protocol = MITMlistener

        try:
            reactor.listenTCP(settings['port'], listenerFactory)
        except:
            print("Ошибка [!]: Ошибка при инициализации порта {0:d}".format(
                settings['port']))
        try:
            reactor.listenTCP(settings['extport'], serverFactory)
        except:
            print("Ошибка [!]: Ошибка при инициализации порта {0:d}".format(
                settings['extport']))

        print("[*]: Инициализация завершена успешно\n")
        print("[*]: Ожидание подключений...\n")
    elif options.__dict__['offlineDict']:
        print("[*]: Демонстрация атаки Offline Dictionary Attack")

        printOptions(offda=True)

        initiatorFactory = protocol.ClientFactory()
        initiatorFactory.protocol = OFFDA

        try:
            reactor.connectTCP(settings['sip'], settings['sport'],
                               initiatorFactory)
        except:
            print("Ошибка [!]: Ошибка при подключении по адресу {0:s}:{1:d}".
                  format(settings['sip'], settings['sport']))

        print("[*]: Инициализация завершена успешно\n")
        print("[*]: Подключение...\n")
    elif options.__dict__['undetectableOnlineDict']:
        print("[*]: Демонстрация атаки Undetectable Online Dictionary Attack")

        printOptions(uonda=True)

        listnerFactory = protocol.ServerFactory()
        listnerFactory.protocol = UONDAlistener

        try:
            reactor.listenTCP(settings['port'], listnerFactory)
        except:
            print("Ошибка [!]: Ошибка при инициализации порта {0:d}".format(
                settings['port']))

        print("[*]: Инициализация завершена успешно\n")
        print("[*]: Ожидание подключения...\n")

    reactor.run()
    def stringReceived(self, data):

        recv_type = ord(data[0])

        if (recv_type == utils.PUT):
            print "Received type: PUT"
            recv_type, messageID, key = struct.unpack("!BBI", data[:6])
            send_type = utils.REPLY_PUT
            value = data[6:]
            print "Key: %d Value: %s" % (key, value)

            hash_key = self.factory.hash(key)
            mapped_ip = self.factory.routingTable.getNode(hash_key)
            print "Hashed key: ", hash_key, " mapped_ip: ", mapped_ip, " is self? ", (
                mapped_ip == self.factory.ip)
            if mapped_ip == self.factory.ip:
                try:
                    ret = ""
                    self.factory.put(key, value)
                except ValueError:
                    send_type = utils.ERROR
                    ret = "Key must be within values %d to %d" % (
                        self.globalRange[0], self.globalRange[1])

                send_string = struct.pack("!BBI", send_type, messageID,
                                          key) + ret
            else:
                send_string = self.forwardRequest(mapped_ip, messageID)

        elif (recv_type == utils.GET):
            print "Received type: GET"
            recv_type, messageID, key = struct.unpack("!BBI", data[:6])
            print "Key: ", key
            mapped_ip = self.factory.routingTable.getNode(
                self.factory.hash(key))
            print "mapped ip to: ", mapped_ip
            if mapped_ip == self.factory.ip:
                print "That is me!"
                try:
                    ret = self.factory.get(key)
                    if not ret:
                        send_type = utils.ERROR
                        ret = "Could not find the key: " + str(key)
                    send_type = utils.REPLY_GET
                except ValueError:
                    send_type = utils.ERROR
                    ret = "Key must be within values %d to %d" % (
                        self.globalRange[0], self.globalRange[1])

                send_string = struct.pack("!BBI", send_type, messageID,
                                          key) + ret
            else:
                "Forwarding..."
                send_string = self.forwardRequest(mapped_ip, messageID)

        elif (recv_type == utils.DELETE):
            print "Received type: DELETE"
            recv_type, messageID, key = struct.unpack("!BBI", data[:6])
            print "Key: ", key
            ret = ""
            send_type = utils.REPLY_DELETE
            mapped_ip = self.factory.routingTable.getNode(
                self.factory.hash(key))
            if mapped_ip == self.factory.ip:
                try:
                    self.factory.delete(key)
                except KeyError:
                    send_type = utils.ERROR
                    ret = "Could not find the key: " + str(key)
                except ValueError:
                    send_type = utils.ERROR
                    ret = "Key must be within values %d to %d" % (
                        self.globalRange[0], self.globalRange[1])

                send_string = struct.pack("!BBI", send_type, messageID,
                                          key) + ret
            else:
                send_string = self.forwardRequest(mapped_ip, messageID)

        elif (recv_type == utils.JOIN_REQUEST):
            print "Received type: JOIN_REQUEST"
            messageID = ord(data[1])

            capacity = self.factory.hashTable.capacity

            if capacity <= 4:
                send_type = utils.ERROR
                ret = "Not enough data to split"
                send_string = struct.pack("!BB", send_type, messageID) + ret
            else:
                num_pdbst = self.factory.hashTable.capacity / 4
                send_type = utils.RANGE_SUGGESTION
                ht_upperBound = self.factory.hashTable.upperBound
                ht_lowerBound = self.factory.hashTable.buckets[
                    -1 * num_pdbst].lowerBound
                ht_range = ht_upperBound - ht_lowerBound

                send_string = struct.pack("!BBI", send_type, messageID,
                                          ht_range)

        elif (recv_type == utils.RANGE_ACCEPT):
            print "Received type: RANGE_ACCEPT"
            messageID = ord(data[1])

            capacity = self.factory.hashTable.capacity
            print "Capacity of ht: ", capacity
            num_pdbst = capacity / 4
            split_index = capacity - num_pdbst
            #split_index = capacity - capacity/10
            new_ht, send_ht = self.factory.hashTable.splitTable(split_index)
            self.factory.hashTable = new_ht

            host_ip = self.transport.getPeer().host

            self.factory.routingTable.addNode(host_ip, send_ht.lowerBound,
                                              send_ht.upperBound)
            self.factory.routingTable.updateRange(
                self.factory.ip, self.factory.hashTable.lowerBound,
                self.factory.hashTable.upperBound)

            print "New routing table:\n", self.factory.routingTable

            for ip in self.factory.routingTable.getAllIP():
                if ip != self.factory.ip and ip != host_ip:
                    b_factory = protocol.ClientFactory()
                    b_factory.protocol = BroadcastProtocol
                    b_factory.routingTable = self.factory.routingTable
                    print "Broadcasting to: ", ip
                    reactor.connectTCP(ip, 1234, b_factory)

            send_type = utils.SEND_CHUNK
            send_string = struct.pack("!BBII", send_type, messageID,
                                      self.factory.globalRange[0],
                                      self.factory.globalRange[1])
            send_string += pickle.dumps(send_ht, -1)

        elif (recv_type == utils.REQUEST_RT):
            print "Received type: REQUEST_RT"
            messageID = ord(data[1])
            send_type = utils.SEND_RT
            send_string = struct.pack("!BB", send_type, messageID)
            send_string += pickle.dumps(self.factory.routingTable)

        elif recv_type == utils.SEND_RT:
            print "Received type: SEND_RT"
            messageID = ord(data[1])

            new_routingTable = pickle.loads(data[2:])
            self.factory.routingTable = new_routingTable
            print "New routing table:\n", new_routingTable

            send_type = utils.RT_ACK
            send_string = struct.pack("!BB", send_type, messageID)

        print "Sending string type: ", type_map[ord(send_string[0])]
        #print "String: ", send_string
        print "String size: ", len(send_string), "\n"
        self.sendString(send_string)
Beispiel #22
0
def main():
    f = protocol.ClientFactory()
    f.protocol = theMagicConch

    reactor.connectTCP(serv_ip, serv_port, f)
    reactor.run()
Beispiel #23
0
def main():
    factory = protocol.ClientFactory()
    factory.protocol = fcp_test_protocol
    reactor.connectTCP('localhost', 9481, factory)
    reactor.run()
Beispiel #24
0
from twisted.internet import reactor, protocol


class FingerClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""

    def connectionMade(self):
        self.transport.write("moshez\r\n")

    def dataReceived(self, data):
        print "Server said:", data
        self.transport.loseConnection()

    def connectionLost(self, reason):
        print "connection lost"
        reactor.stop()


if __name__ == '__main__':
    factory = protocol.ClientFactory()
    factory.protocol = FingerClient
    reactor.connectTCP("localhost", 2079, factory)
    reactor.run()
Beispiel #25
0
    print "DC starting up..."
    last_epoch_start = int(time.time()) / epoch

    def epoch_change():
        global last_epoch_start
        global should_send
        now = int(time.time()) / epoch
        if now > last_epoch_start:
            last_epoch_start = now
            print "Epoch Change!\n"
            reactor.connectSSL(tallyhost, int(tallyport), sendtallyfactory,
                               ssl.ClientContextFactory())

    epoch_check = task.LoopingCall(epoch_change)
    epoch_check.start(1)
    sendtallyfactory = protocol.ClientFactory()
    sendtallyfactory.protocol = exitStatSend

    c_factory = protocol.ClientFactory()
    c_factory.protocol = exitRegister
    time.sleep(dc_reg_delay)
    for host, port in tkg_info:
        reactor.connectSSL(host, int(port), c_factory,
                           ssl.ClientContextFactory())

    s_factory = protocol.ServerFactory()
    s_factory.protocol = exitListener
    reactor.listenTCP(int(args.port), s_factory,
                      interface='127.0.0.1')  # Local Tor connection
    print "DC ready!"
    reactor.run()
Beispiel #26
0
 def connectionMade(self):
     factory = protocol.ClientFactory()
     factory.protocol = ClientProtocol
     factory.server = self
     reactor.connectTCP('localhost', 1234, factory)
Beispiel #27
0
    def connectionMade(self):
        self.client_factory = protocol.ClientFactory()
        self.client_factory.protocol = ClientProtocol
        self.client_factory.server = self

        reactor.connectTCP(HOST, TARGET_PORT, self.client_factory)