olokki
olokki

Reputation: 1027

paramiko server mode port forwarding

I need to implement a ssh server using paramiko that only handles '-R' port forwarding requests like this:

ssh -N -T -R 40005:destination_host:22 [email protected]

So far from what i understand i'll have to implement ServerInterface.check_port_forward_request and at some point after, create a socket and listen to the specified port. Any data that comes through the Channel/Connection go to Connection/Channel respectively

class Server (paramiko.ServerInterface):
    .
    .
    .
    def check_port_forward_request(self, address, port):
        'Check if the requested port forward is allowed'
        ...
        return port

def handler(chan, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', port))
    sock.listen(1)
    conn, addr = s.accept()    

    while True:
        r, w, x = select.select([conn, chan], [], [])
        if conn in r:
            data = conn.recv(1024)
            if len(data) == 0:
                break
            chan.send(data)
        if chan in r:
            data = chan.recv(1024)
            if len(data) == 0:
                break
            conn.send(data)
    chan.close()
    conn.close()
    verbose('Tunnel closed from %r' % (chan.origin_addr,))

thr = threading.Thread(target=handler, args=(chan,server_port))
thr.setDaemon(True)
thr.start()

Is this the general idea behind implementing server-side paramiko ssh port forwarding? Should i start the thread inside check_port_forward_request or somewhere else?

Upvotes: 6

Views: 2296

Answers (1)

Schof
Schof

Reputation: 6589

Here's a working example from Paramiko's source of reverse port forwarding:

https://github.com/paramiko/paramiko/blob/master/demos/rforward.py

Upvotes: 1

Related Questions