Ejemplo n.º 1
0
	def run(self, port=8023, ip=''):
		self._s = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
		self._s.set_reuse_addr()
		self._s.bind((ip, port))
		self._s.listen(1024)

		port = self._s.getsockname()[1]
		self.info('Backdoor listening on port %d' % (port,))
		
		while not self._exit:
			try:
				conn, addr = self._s.accept()
			except coro.CoroutineSocketWake:
				continue

			client = BackDoorClient(args = (conn, addr))
			client.start()

		self.info('Backdoor exiting (children: %d)' % self.child_count())

		self._s.close()
		self._s = None

		for child in self.child_list():
			child.shutdown()

		self.child_wait()
		return None
Ejemplo n.º 2
0
def smtp_tls_server():
    sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('0.0.0.0', 25))
    sock.listen(5)
    while True:
        conn, addr = sock.accept()
        coro.spawn(smtp_tls_server_session, conn)
Ejemplo n.º 3
0
def serve(port=None,
          ip='',
          unix_path=None,
          welcome_message=None,
          global_dict=None,
          client_class=None):
    """Backdoor server function.

    This function will listen on the backdoor socket and spawn new threads for
    each connection.

    :Parameters:
        - `port`: The IPv4 port to listen on (defaults to automatically choose
          an unused port between 8023->8033).  May also be a list of ports.
        - `ip`: The IP to listen on.  Defaults to all IP's.
        - `unix_path`: The unix path to listen on.  If this is specified, then
          it will use unix-domain sockets, otherwise it will use IPv4 sockets.
        - `welcome_message`: A welcome message to display when a user logs in.
        - `global_dict`: The global dictionary to use for client sessions.
    """
    import errno
    if unix_path:
        try:
            os.remove(unix_path)
        except OSError, why:
            if why[0] == errno.ENOENT:
                pass
            else:
                raise
        s = coro.make_socket(coro.PF.LOCAL, coro.SOCK.STREAM)
        s.bind(unix_path)
        coro.print_stderr('Backdoor started on unix socket %s\n' % unix_path)
Ejemplo n.º 4
0
 def make_data_channel (self):
     # In PASV mode, the connection may or may _not_ have been made
     # yet.  [although in most cases it is... FTP Explorer being
     # the only exception I've yet seen].  This gets somewhat confusing
     # because things may happen in any order...
     pa = self.passive_acceptor
     if pa:
         conn, addr = pa.accept()
         self.close_passive_acceptor()
         return conn, addr
     else:
         # not in PASV mode.
         ip, port = self.client_addr
         cdc = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
         if self.bind_local_minus_one:
             cdc.bind ((self.server.ip, self.server.port - 1))
         else:
             # using random port number
             cdc.bind ((self.server.ip, 0))
         try:
             cdc.connect (self.client_addr)
         except OSError, why:
             cdc.close()
             cdc = None
             self.respond ("425 Can't build data connection: %s" % why.strerror)
         return cdc, self.client_addr
Ejemplo n.º 5
0
    def run(self, port=8023, ip=''):
        self._s = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
        self._s.set_reuse_addr()
        self._s.bind((ip, port))
        self._s.listen(1024)

        port = self._s.getsockname()[1]
        self.info('Backdoor listening on port %d' % (port, ))

        while not self._exit:
            try:
                conn, addr = self._s.accept()
            except coro.CoroutineSocketWake:
                continue

            client = BackDoorClient(args=(conn, addr))
            client.start()

        self.info('Backdoor exiting (children: %d)' % self.child_count())

        self._s.close()
        self._s = None

        for child in self.child_list():
            child.shutdown()

        self.child_wait()
        return None
Ejemplo n.º 6
0
    def test_invalid_ip(self):
        from coro.dns.exceptions import DNS_Hard_Error

        sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.assertRaises(DNS_Hard_Error, sock.connect, ("123", 80))
        self.assertRaises(ValueError, sock.connect_addr, ("123", 80), False)
        self.assertRaises(TypeError, sock.connect, (123, 80))
Ejemplo n.º 7
0
def smtp_tls_server():
    sock = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
    sock.bind (('0.0.0.0', 25))
    sock.listen (5)
    while True:
        conn, addr = sock.accept()
        coro.spawn (smtp_tls_server_session, conn)
Ejemplo n.º 8
0
def serve (port=None, ip='', unix_path=None, welcome_message=None, global_dict=None, client_class=None):
    """Backdoor server function.

    This function will listen on the backdoor socket and spawn new threads for
    each connection.

    :Parameters:
        - `port`: The IPv4 port to listen on (defaults to automatically choose
          an unused port between 8023->8033).  May also be a list of ports.
        - `ip`: The IP to listen on.  Defaults to all IP's.
        - `unix_path`: The unix path to listen on.  If this is specified, then
          it will use unix-domain sockets, otherwise it will use IPv4 sockets.
        - `welcome_message`: A welcome message to display when a user logs in.
        - `global_dict`: The global dictionary to use for client sessions.
    """
    import errno
    if unix_path:
        try:
            os.remove (unix_path)
        except OSError, why:
            if why[0] == errno.ENOENT:
                pass
            else:
                raise
        s = coro.make_socket (coro.PF.LOCAL, coro.SOCK.STREAM)
        s.bind (unix_path)
        coro.print_stderr('Backdoor started on unix socket %s\n' % unix_path)
Ejemplo n.º 9
0
def serve (port):
    s = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
    s.set_reuse_addr()
    s.bind (('', port))
    s.listen (8192)
    while 1:
        conn, addr = s.accept()
        coro.spawn (service_client, conn, addr)
Ejemplo n.º 10
0
 def connect():
     s = coro.make_socket (coro.AF.INET, socket.SOCK_STREAM)
     coro.with_timeout (5, s.connect, ('127.0.0.1', server.port))
     howdy = coro.with_timeout (5, s.recv, 100)
     self.assertEqual (howdy, 'howdy!\r\n')
     count -= 1
     if count == 0:
         server_thread.raise_exception(coro.Shutdown)
Ejemplo n.º 11
0
 def test_bind_wrong_af_6to4(self):
     sock = coro.make_socket(socket.AF_INET6, socket.SOCK_STREAM)
     self.assertEquals(sock.domain, socket.AF_INET6)
     self.assertRaises(
         ValueError,
         sock.bind,
         ("1.1.1.1", 5010),
     )
Ejemplo n.º 12
0
def serve(port):
    s = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
    s.set_reuse_addr()
    s.bind(('', port))
    s.listen(8192)
    while 1:
        conn, addr = s.accept()
        coro.spawn(service_client, conn, addr)
Ejemplo n.º 13
0
 def test_bind_wrong_af_4to6(self):
     sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.assertEquals(sock.domain, socket.AF_INET)
     self.assertRaises(
         ValueError,
         sock.bind,
         ("2001::1", 5010),
     )
Ejemplo n.º 14
0
 def testit(family, address, block_sends, block_receives, expected_results):
     s = coro.make_socket(family, socket.SOCK_STREAM)
     server.block_sends = block_sends
     coro.with_timeout(5, s.connect, (address, server.port))
     blocks = coro.with_timeout(5, s.readv, block_receives)
     self.assertEqual(len(blocks), len(expected_results))
     for block, expected_block in zip(blocks, expected_results):
         self.assertEqual(block, expected_block)
Ejemplo n.º 15
0
def serve (port=None, ip='127.0.0.1', unix_path=None, welcome_message=None, global_dict=None):
    import errno
    if unix_path:
        try:
            os.remove(unix_path)
        except OSError as why:
            if why[0] == errno.ENOENT:
                pass
            else:
                raise
        try:
            s = coro.make_socket (socket.AF_UNIX, socket.SOCK_STREAM)
            s.bind(unix_path)
        except OSError:
            coro.print_stderr('Error starting up backdoor on unix socket %s\n' % unix_path)
            raise
        coro.print_stderr('Backdoor started on unix socket %s\n' % unix_path)
    else:
        s = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
        s.set_reuse_addr()
        if port is None:
            ports = xrange(8023, 8033)
        else:
            if isinstance(port, types.IntType):
                ports = [port]
            else:
                ports = port
        bound = 0
        for i in ports:
            try:
                s.bind ((ip, i))
                bound = 1
                break
            except (OSError, socket.error) as why:
                if why[0] != errno.EADDRINUSE:
                    raise OSError(why)
        if not bound:
            raise Exception("couldn't bind a port (try not specifying a port)")
        coro.print_stderr('Backdoor started on port %d\n' % i)
    s.listen (1024)
    while True:
        conn, addr = s.accept()
        coro.print_stderr ('incoming connection from %r\n' % (conn.getsockname(),))
        thread = coro.spawn (client, conn, addr, welcome_message, global_dict)
        thread.set_name('backdoor session')
Ejemplo n.º 16
0
 def testit(family, address, block_sends, block_receives,
            expected_results):
     s = coro.make_socket(family, socket.SOCK_STREAM)
     server.block_sends = block_sends
     coro.with_timeout(5, s.connect, (address, server.port))
     blocks = coro.with_timeout(5, s.readv, block_receives)
     self.assertEqual(len(blocks), len(expected_results))
     for block, expected_block in zip(blocks, expected_results):
         self.assertEqual(block, expected_block)
Ejemplo n.º 17
0
 def test_invalid_ip(self):
     from coro.dns.exceptions import DNS_Hard_Error
     sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.assertRaises(DNS_Hard_Error, sock.connect, ('123', 80))
     self.assertRaises(ValueError, sock.connect_addr, ('123', 80), False)
     self.assertRaises(
         TypeError,
         sock.connect,
         (123, 80),
     )
Ejemplo n.º 18
0
 def __init__(self, ip=None, port=22, bind_ip=None, hostname=None, sock=None):
     self.ip = ip
     self.port = port
     self.bind_ip = bind_ip
     self.hostname = hostname
     if sock is None:
         self.s = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
     else:
         self.s = sock
         self.peer = self.s.getpeername()
Ejemplo n.º 19
0
 def __init__ (self, local_ip=None):
     """__init__(local_ip=None) -> ftp_client
     Creates a new ftp_client.  Binds to the local_ip if it is given.
     NOTE: You MUST del the stream object when you are done, or this will leak.
     """
     self.local_ip = local_ip
     self.s = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
     if local_ip:
         self.s.bind((local_ip,0))
     self.stream = read_stream.stream_reader (self.recv)
Ejemplo n.º 20
0
    def serve(self, address, family):
        self.s = coro.make_socket(family, socket.SOCK_STREAM)
        self.s.bind((address, 0))
        self.bound_ip, self.port = self.s.getsockname()
        self.s.set_reuse_addr()
        self.s.listen(5)

        s, addr = self.s.accept()
        session = TestSession(s, addr)
        coro.spawn(session.run)
        self.accepted_from = s.getsockname()[0]
Ejemplo n.º 21
0
    def serve(self, address, family):
        self.s = coro.make_socket(family, socket.SOCK_STREAM)
        self.s.bind((address, 0))
        self.bound_ip, self.port = self.s.getsockname()
        self.s.set_reuse_addr()
        self.s.listen(5)

        s, addr = self.s.accept()
        session = TestSession(s, addr)
        coro.spawn(session.run)
        self.accepted_from = s.getsockname()[0]
Ejemplo n.º 22
0
def make_socket_for_ip(ip, stype=socket.SOCK_STREAM):
    """Create a socket object with the correct address family for ip.

    :Parameters:
        - `ip`: An IP address as a string
        - `stype`: The socket type (see `SOCK`).

    :Return:
        Returns a socket object.

    :Exceptions:
        - `OSError`: OS-level error.
        - `ValueError`: Invalid IP address.
    """

    if net_ip.is_ipv4(ip):
        return coro.make_socket(socket.AF_INET, stype)
    elif net_ip.is_ipv6(ip):
        return coro.make_socket(socket.AF_INET6, stype)
    else:
        raise ValueError("Invalid IP address")
Ejemplo n.º 23
0
    def create(self, sock=None, verify=None):
        self.ssl = self.ctx.ssl()

        if sock is None:
            self.sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

        if verify:
            self.ssl.set_verify(sslip.SSL_VERIFY_PEER)

        self.ssl.set_fd(self.sock.fileno())
Ejemplo n.º 24
0
    def create (self, sock=None, verify=None):
        self.ssl = self.ctx.ssl()

        if sock is None:
            self.sock = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

        if verify:
            self.ssl.set_verify (sslip.SSL_VERIFY_PEER)

        self.ssl.set_fd (self.sock.fileno())
Ejemplo n.º 25
0
 def serve(self, family, address):
     self.s = coro.make_socket(family, socket.SOCK_STREAM)
     self.s.bind((address, 0))
     self.port = self.s.getsockname()[1]
     self.s.set_reuse_addr()
     self.s.listen(5)
     while True:
         try:
             s, addr = self.s.accept()
         except coro.Shutdown:
             break
         session = TestSession(s, addr, self.block_sends)
         coro.spawn(session.run)
Ejemplo n.º 26
0
def serve (address='/tmp/debug.sock', global_dict=None):
    "serve a debugging console.  address := a string (for a unix socket) or an (ip, port) pair."
    import errno
    global dbg_conn
    if isinstance(address, basestring):
        try:
            os.remove (address)
        except OSError, why:
            if why[0] == errno.ENOENT:
                pass
            else:
                raise
        s = coro.make_socket (coro.PF.LOCAL, coro.SOCK.STREAM)
Ejemplo n.º 27
0
 def testit(family, address, block_sends, expected_buffer_result, expected_return):
     global finished
     finished = coro.condition_variable()
     s = coro.make_socket(family, socket.SOCK_STREAM)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, send_buffer_size)
     coro.with_timeout(5, s.connect, (address, server.port))
     blocks = [ big_block[:size] for size in block_sends ]
     rc = coro.with_timeout(5, s.writev, blocks)
     s.close()
     if finished is not None:
         coro.with_timeout(5, finished.wait)
     self.assertEqual(expected_buffer_result, current_buffer)
     self.assertEqual(expected_return, rc)
Ejemplo n.º 28
0
 def serve(self, family, address):
     self.s = coro.make_socket(family, socket.SOCK_STREAM)
     self.s.bind((address, 0))
     self.port = self.s.getsockname()[1]
     self.s.set_reuse_addr()
     self.s.listen(5)
     while True:
         try:
             s, addr = self.s.accept()
         except coro.Shutdown:
             break
         session = TestSession(s, addr, self.block_sends)
         coro.spawn(session.run)
Ejemplo n.º 29
0
 def test_bind_af_unspec(self):
     sock = coro.make_socket(socket.AF_INET6, socket.SOCK_STREAM)
     sock.domain = socket.AF_UNSPEC
     self.assertRaises(
         ValueError,
         sock.bind,
         ("1.1.1.1", 5010),
     )
     self.assertRaises(
         ValueError,
         sock.bind,
         ("", 5010),
     )
Ejemplo n.º 30
0
 def serve(self, family, address):
     self.s = coro.make_socket(family, socket.SOCK_STREAM)
     self.s.setsockopt (socket.SOL_SOCKET, socket.SO_RCVBUF, recv_buffer_size)
     self.s.bind((address, 0))
     self.port = self.s.getsockname()[1]
     self.s.set_reuse_addr()
     self.s.listen(5)
     while 1:
         try:
             s, addr = self.s.accept()
         except coro.Shutdown:
             break
         session = TestSession(s, addr)
         coro.spawn(session.run)
Ejemplo n.º 31
0
 def testit(family, address, block_sends, expected_buffer_result,
            expected_return):
     global finished
     finished = coro.condition_variable()
     s = coro.make_socket(family, socket.SOCK_STREAM)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, send_buffer_size)
     coro.with_timeout(5, s.connect, (address, server.port))
     blocks = [big_block[:size] for size in block_sends]
     rc = coro.with_timeout(5, s.writev, blocks)
     s.close()
     if finished is not None:
         coro.with_timeout(5, finished.wait)
     self.assertEqual(expected_buffer_result, current_buffer)
     self.assertEqual(expected_return, rc)
Ejemplo n.º 32
0
 def make_data_channel (self):
     global connect_timeout
     if self.pasv_mode:
         reply = self.command ('PASV', '2')
         ip, port = self.parse_pasv_reply (reply)
         dc = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
         if self.local_ip:
             dc.bind((self.local_ip, 0))
         if self.debug:
             coro.print_stderr ('connecting to %s:%s\n' % (ip, port))
         coro.with_timeout (connect_timeout, dc.connect, (ip, port))
         return dc
     else:
         raise ftp_error, "non-pasv transfers not yet implemented"
Ejemplo n.º 33
0
    def make_socket(self, *args, **kwargs):
        """Make socket in both coro and non-coro environments.

        Returns socket, send function; the latter accounts for
        different behavior between socket.send and coro_socket.send
        by using self.sendall instead."""

        if GOT_CORO and coro.coro_is_running():
            sock = coro.make_socket(*args, **kwargs)
            sender = sock.send
        else:
            sock = socket.socket(*args, **kwargs)
            sender = self.sendall

        return (sock, sender)
Ejemplo n.º 34
0
 def serve(self, family, address):
     self.s = coro.make_socket(family, socket.SOCK_STREAM)
     self.s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF,
                       recv_buffer_size)
     self.s.bind((address, 0))
     self.port = self.s.getsockname()[1]
     self.s.set_reuse_addr()
     self.s.listen(5)
     while 1:
         try:
             s, addr = self.s.accept()
         except coro.Shutdown:
             break
         session = TestSession(s, addr)
         coro.spawn(session.run)
Ejemplo n.º 35
0
    def make_socket(self, *args, **kwargs):
        """Make socket in both coro and non-coro environments.

        Returns socket, send function; the latter accounts for
        different behavior between socket.send and coro_socket.send
        by using self.sendall instead."""

        if GOT_CORO and coro.coro_is_running():
            sock = coro.make_socket(*args, **kwargs)
            sender = sock.send
        else:
            sock = socket.socket(*args, **kwargs)
            sender = self.sendall

        return (sock, sender)
Ejemplo n.º 36
0
 def cmd_pasv (self, line):
     # careful to close one that might already be there...
     self.close_passive_acceptor()
     ps = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
     self.passive_acceptor = ps
     ps.bind ((self.conn.getsockname()[0], 0))
     ps.listen (1)
     (ip, port) = ps.getsockname()
     self.respond (
         '227 Entering Passive Mode (%s,%d,%d)' % (
             ','.join (ip.split ('.')),
             port/256,
             port%256
             )
         )
Ejemplo n.º 37
0
 def serve (self, family, address):
     self.s = coro.make_socket (family, socket.SOCK_STREAM)
     self.s.bind ((address, 0))
     self.port = self.s.getsockname()[1]
     self.s.set_reuse_addr()
     self.s.listen (5)
     while True:
         try:
             coro.write_stderr ('accepting...\n')
             conns = self.s.accept_many (5)
             coro.write_stderr ('...after: conns=%r\n' % (conns,))
         except coro.Shutdown:
             break
         for s, addr in conns:
             session = TestSession (s, addr)
             coro.spawn (session.run)
Ejemplo n.º 38
0
def smtp_tls_session(host,
                     port='25',
                     fromaddr='*****@*****.**',
                     to='*****@*****.**'):
    print "smtp tls test client"
    sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
    print "host=%r port=%r" % (host, port)
    port = string.atoi(port)
    sock.connect((host, port))
    print sock.recv(8192)
    sock.send('EHLO fang\r\n')
    print sock.recv(8192)
    sock.send('STARTTLS\r\n')
    print sock.recv(8192)
    ctx = coro_ssl.ssl_ctx(sslip.SSLV2_CLIENT_METHOD)
    client = coro_ssl.ssl_sock(ctx)
    client.create(sock=sock)
    # client.ssl.set_connect_state()
    try:
        coro.print_stderr('calling ssl_connect()\n')
        client.ssl_connect()
        coro.print_stderr('ssl_connect done()\n')
    except sslip.Error:
        coro.print_stderr("TLS negotiation failed\n")
        coro.print_stderr("hit <return> to attempt fallback\n")
        client.shutdown()
        raw_input()
    else:
        sock = client
    print "ssl_connect() finished"
    sock.send('HELP\r\n')
    print sock.recv(8192)
    sock.send('MAIL FROM:<' + fromaddr + '>\r\n')
    print sock.recv(8192)
    sock.send('RCPT TO:<' + to + '>\r\n')
    print sock.recv(8192)
    sock.send('DATA\r\n')
    print sock.recv(8192)
    sock.send(
        'From: ' + fromaddr +
        '\r\nSubject: testing STARTTLS\r\n\r\nHi there.  I was encrypted\r\n.\r\n'
    )
    print sock.recv(8192)
    sock.send('QUIT\r\n')
    print sock.recv(8192)
    sock.close()
    coro._exit = 1
Ejemplo n.º 39
0
def serve (port=None, ip='127.0.0.1', unix_path=None, welcome_message=None, global_dict=None):
    import errno
    if unix_path:
        try:
            os.remove(unix_path)
        except OSError, why:
            if why[0]==errno.ENOENT:
                pass
            else:
                raise
        try:
            s = coro.make_socket (socket.AF_UNIX, socket.SOCK_STREAM)
            s.bind(unix_path)
        except OSError:
            coro.print_stderr('Error starting up backdoor on unix socket %s\n' % unix_path)
            raise
        coro.print_stderr('Backdoor started on unix socket %s\n' % unix_path)
Ejemplo n.º 40
0
 def _run (self):
     """Listens on the FTP port accepting connections and spawning sessions."""
     self.thread_id = coro.current().thread_id()
     s = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
     try:
         s.set_reuse_addr()
         done = 0
         while not done:
             for x in xrange (5):
                 try:
                     was_eaddrinuse = 0
                     s.bind ((self.ip, self.port))
                 except OSError, why:
                     if why[0] == errno.EACCES:
                         coro.print_stderr(
                             'Access denied binding to %s:%i.  Are you running as root?\n' % (self.ip, self.port))
                         return
                     elif why[0] == errno.EADDRINUSE:
                         was_eaddrinuse = 1
                     elif why[0] != errno.EADDRNOTAVAIL:
                         raise
                 else:
                     done = 1
                     break
                 coro.sleep_relative (1)
             else:
                 coro.print_stderr ("cannot bind to %s:%d after 5 attempts\n" % (self.ip, self.port))
                 if was_eaddrinuse:
                     qlog.write('FTPD.PORT_IN_USE',
                                self.ip, str(self.port))
                 coro.sleep_relative (15)
         s.listen (1024)
         while 1:
             conn_list = s.accept_many()
             for conn, addr in conn_list:
                 qlog.write('FTPD.CONNECTION', self.session_id, addr[0], self.ip)
                 session = self.channel (self, conn, addr, self.session_id)
                 self.session_id += 1
                 thread = coro.spawn (session.run)
                 thread.set_name (
                     "%s_%d" % (
                         session.__class__.__name__,
                         thread.thread_id()
                     )
                 )
                 self.clients.append(session)
Ejemplo n.º 41
0
def smtp_tls_session (
    host,
    port='25',
    fromaddr='*****@*****.**',
    to='*****@*****.**'
):
    print "smtp tls test client"
    sock = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
    print "host=%r port=%r" % (host, port)
    port = string.atoi(port)
    sock.connect ((host, port))
    print sock.recv (8192)
    sock.send ('EHLO fang\r\n')
    print sock.recv (8192)
    sock.send ('STARTTLS\r\n')
    print sock.recv (8192)
    ctx = coro_ssl.ssl_ctx (sslip.SSLV2_CLIENT_METHOD)
    client = coro_ssl.ssl_sock (ctx)
    client.create (sock=sock)
    # client.ssl.set_connect_state()
    try:
        coro.print_stderr ('calling ssl_connect()\n')
        client.ssl_connect()
        coro.print_stderr ('ssl_connect done()\n')
    except sslip.Error:
        coro.print_stderr ("TLS negotiation failed\n")
        coro.print_stderr ("hit <return> to attempt fallback\n")
        client.shutdown()
        raw_input()
    else:
        sock = client
    print "ssl_connect() finished"
    sock.send ('HELP\r\n')
    print sock.recv (8192)
    sock.send ('MAIL FROM:<' + fromaddr + '>\r\n')
    print sock.recv (8192)
    sock.send ('RCPT TO:<' + to + '>\r\n')
    print sock.recv (8192)
    sock.send ('DATA\r\n')
    print sock.recv (8192)
    sock.send ('From: ' + fromaddr + '\r\nSubject: testing STARTTLS\r\n\r\nHi there.  I was encrypted\r\n.\r\n')
    print sock.recv (8192)
    sock.send ('QUIT\r\n')
    print sock.recv (8192)
    sock.close()
    coro._exit = 1
Ejemplo n.º 42
0
 def _run (self):
     """Listens on the FTP port accepting connections and spawning sessions."""
     self.thread_id = coro.current().thread_id()
     s = coro.make_socket (socket.AF_INET, socket.SOCK_STREAM)
     try:
         s.set_reuse_addr()
         done = 0
         while not done:
             for x in xrange (5):
                 try:
                     was_eaddrinuse = 0
                     s.bind ((self.ip, self.port))
                 except OSError, why:
                     if why[0] == errno.EACCES:
                         coro.print_stderr('Access denied binding to %s:%i.  Are you running as root?\n' % (self.ip, self.port))
                         return
                     elif why[0] == errno.EADDRINUSE:
                         was_eaddrinuse = 1
                     elif why[0] != errno.EADDRNOTAVAIL:
                         raise
                 else:
                     done = 1
                     break
                 coro.sleep_relative (1)
             else:
                 coro.print_stderr ("cannot bind to %s:%d after 5 attempts\n" % (self.ip, self.port))
                 if was_eaddrinuse:
                     qlog.write('FTPD.PORT_IN_USE',
                                self.ip, str(self.port))
                 coro.sleep_relative (15)
         s.listen (1024)
         while 1:
             conn_list = s.accept_many()
             for conn, addr in conn_list:
                 qlog.write('FTPD.CONNECTION', self.session_id, addr[0], self.ip)
                 session = self.channel (self, conn, addr, self.session_id)
                 self.session_id += 1
                 thread = coro.spawn (session.run)
                 thread.set_name (
                     "%s_%d" % (
                         session.__class__.__name__,
                         thread.thread_id()
                         )
                     )
                 self.clients.append(session)
Ejemplo n.º 43
0
    def _test(self, address, family):
        server = TestServer()
        server_thread = coro.spawn(server.serve, address, family)
        # Give the server a chance to start.
        coro.yield_slice()
        self.assertEqual(server.bound_ip, address)

        sock = coro.make_socket(family, socket.SOCK_STREAM)
        sock.connect((address, server.port))

        coro.yield_slice()

        # Double checking that everyone thinks they're connected
        # to the same peer
        self.assertEqual(server.accepted_from, address)
        self.assertEqual(sock.getpeername()[0], server.accepted_from)

        self.do_work(sock)
Ejemplo n.º 44
0
    def _test(self, address, family):
        server = TestServer()
        server_thread = coro.spawn(server.serve, address, family)
        # Give the server a chance to start.
        coro.yield_slice()
        self.assertEqual(server.bound_ip, address)

        sock = coro.make_socket(family, socket.SOCK_STREAM)
        sock.connect((address, server.port))

        coro.yield_slice()

        # Double checking that everyone thinks they're connected
        # to the same peer
        self.assertEqual(server.accepted_from, address)
        self.assertEqual(sock.getpeername()[0], server.accepted_from)

        self.do_work(sock)
Ejemplo n.º 45
0
	def run(self):
		self.sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.sock.bind(self.addr)
		self.sock.listen(128)

		self.info('Listening to address: %r' % (self.addr,))
	
		while not self.exit:
			try:
				conn, addr = self.sock.accept()
			except coro.CoroutineSocketWake:
				continue
			except Exception, e:
				self.error('Exception from accept: %r', e)
				break

			eclnt = EchoClient(addr = addr, sock = conn)
			eclnt.start()
Ejemplo n.º 46
0
 def test_invalid_ip(self):
     sock = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.assertRaises(ValueError, sock.connect, (('123', 80), ))
     self.assertRaises(ValueError, sock.connect, ((123, 80), ))
Ejemplo n.º 47
0
 def test_bind_empty_ip_v6(self):
     sock = coro.make_socket(socket.AF_INET6, socket.SOCK_STREAM)
     sock.bind(("", 5010))
     self.assertEquals(sock.domain, socket.AF_INET6)
Ejemplo n.º 48
0
 def __init__(self):
     self.s = coro.make_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.buffer = ''
     self.lines = []
Ejemplo n.º 49
0
 def test_getsockname_v6(self):
     sock = coro.make_socket(socket.AF_INET6, socket.SOCK_STREAM)
     sock.bind(("", 5555))
     sn = sock.getsockname()
     self.assertEquals(sn[0], "::")
     self.assertEquals(sn[1], 5555)
Ejemplo n.º 50
0
     - `global_dict`: The global dictionary to use for client sessions.
 """
 import errno
 if unix_path:
     try:
         os.remove(unix_path)
     except OSError, why:
         if why[0] == errno.ENOENT:
             pass
         else:
             raise
     s = coro.make_socket(coro.PF.LOCAL, coro.SOCK.STREAM)
     s.bind(unix_path)
     coro.print_stderr('Backdoor started on unix socket %s\n' % unix_path)
 else:
     s = coro.make_socket(coro.PF.INET, coro.SOCK.STREAM)
     s.set_reuse_addr()
     if port is None:
         ports = xrange(8023, 8033)
     else:
         if type(port) is int:
             ports = [port]
         else:
             ports = port
     for i in ports:
         try:
             s.bind((ip, i))
             coro.print_stderr('Backdoor started on port %d\n' % i)
             break
         except OSError, why:
             if why[0] != errno.EADDRINUSE:
Ejemplo n.º 51
0
def serve (address='/tmp/debug.sock', global_dict=None):
    "serve a debugging console.  address := a string (for a unix socket) or an (ip, port) pair."
    import errno
    global dbg_conn
    if isinstance(address, basestring):
        try:
            os.remove (address)
        except OSError, why:
            if why[0] == errno.ENOENT:
                pass
            else:
                raise
        s = coro.make_socket (coro.PF.LOCAL, coro.SOCK.STREAM)
    else:
        ip, port = address
        s = coro.make_socket (coro.PF.INET, coro.SOCK.STREAM)
        s.set_reuse_addr()

    s.bind (address)
    LOG ('started', address)
    s.listen (10)

    while 1:
        conn, addr = s.accept()
        LOG ('open', conn.getpeername())
        dbg_conn = Client (conn)


if __name__ == '__main__':
    def thingy (i):
        n = 0
Ejemplo n.º 52
0
 def test_bind_af_unspec(self):
     sock = coro.make_socket(socket.AF_INET6, socket.SOCK_STREAM)
     sock.domain = socket.AF_UNSPEC
     self.assertRaises(ValueError, sock.bind, ("1.1.1.1", 5010),)
     self.assertRaises(ValueError, sock.bind, ("", 5010),)
Ejemplo n.º 53
0
 def test_getsockname_v6(self):
     sock = coro.make_socket(socket.AF_INET6, socket.SOCK_STREAM)
     sock.bind(("", 5555))
     sn = sock.getsockname()
     self.assertEquals(sn[0], "::")
     self.assertEquals(sn[1], 5555)