1#!/usr/bin/env python3.6
2#
3# Copyright (c) 2013-2018 by Ron Frederick <ronf@timeheart.net> and others.
4#
5# This program and the accompanying materials are made available under
6# the terms of the Eclipse Public License v2.0 which accompanies this
7# distribution and is available at:
8#
9#     http://www.eclipse.org/legal/epl-2.0/
10#
11# This program may also be made available under the following secondary
12# licenses when the conditions for such availability set forth in the
13# Eclipse Public License v2.0 are satisfied:
14#
15#    GNU General Public License, Version 2.0, or any later versions of
16#    that license
17#
18# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
19#
20# Contributors:
21#     Ron Frederick - initial implementation, API, and documentation
22
23# To run this program, the file ``ssh_host_key`` must exist with an SSH
24# private key in it to use as a server host key. An SSH host certificate
25# can optionally be provided in the file ``ssh_host_key-cert.pub``.
26#
27# The file ``ssh_user_ca`` must exist with a cert-authority entry of
28# the certificate authority which can sign valid client certificates.
29
30import asyncio, asyncssh, sys
31
32class MySSHTCPSession(asyncssh.SSHTCPSession):
33    def connection_made(self, chan):
34        self._chan = chan
35
36    def data_received(self, data, datatype):
37        self._chan.write(data)
38
39class MySSHServer(asyncssh.SSHServer):
40    def connection_requested(self, dest_host, dest_port, orig_host, orig_port):
41        if dest_port == 7:
42            return MySSHTCPSession()
43        else:
44            raise asyncssh.ChannelOpenError(
45                      asyncssh.OPEN_ADMINISTRATIVELY_PROHIBITED,
46                      'Only echo connections allowed')
47
48async def start_server():
49    await asyncssh.create_server(MySSHServer, '', 8022,
50                                 server_host_keys=['ssh_host_key'],
51                                 authorized_client_keys='ssh_user_ca')
52
53loop = asyncio.get_event_loop()
54
55try:
56    loop.run_until_complete(start_server())
57except (OSError, asyncssh.Error) as exc:
58    sys.exit('SSH server failed: ' + str(exc))
59
60loop.run_forever()
61