-
Notifications
You must be signed in to change notification settings - Fork 1
/
ssh_server.py
180 lines (155 loc) · 5.56 KB
/
ssh_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
__filename__ = "ssh_server.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "1.0.0"
__maintainer__ = "Bob Mottram"
__email__ = "[email protected]"
__status__ = "Production"
__module_group__ = "Command Interface"
import paramiko
import threading
import socket
import subprocess
import time
class SSHServer(paramiko.ServerInterface):
"""Implements a SSH server
"""
def __init__(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self, username, password):
self.username = username
self.password = password
return paramiko.AUTH_SUCCESSFUL
def check_channel_pty_request(self, channel: paramiko.Channel, term: bytes,
width: int, height: int, pixelwidth: int,
pixelheight: int, modes: bytes) -> bool:
return False
def check_channel_shell_request(self, channel: paramiko.Channel) -> bool:
return True
def check_channel_exec_request(self, channel: paramiko.Channel,
command) -> bool:
print('command: ' + str(command))
return True
def _handle_ssh_connection(t, chan, parent, server):
"""Handles an incoming ssh connection
"""
if not chan:
return
chan.sendall("Connected...\n")
parent._id = parent.get_next_id()
curr_id = parent._id
parent.add_new_player(parent._CLIENT_SSH, chan, chan,
server.username, server.password)
# clear any credentials
server.username = server.password = None
while 1:
command = chan.recv(4096)
if not t.is_active() or command in (b'exit\n', b'quit\n'):
parent.handle_disconnect(curr_id)
chan.shutdown(2)
chan.close()
break
try:
if curr_id >= 0:
message = command.decode('utf-8').strip()
parent.receive_message(curr_id, message)
except KeyboardInterrupt as kexc:
print('KeyboardInterrupt: ' + str(kexc))
parent.handle_disconnect(curr_id)
chan.shutdown(2)
chan.close()
break
except subprocess.CalledProcessError:
chan.sendall(b'Unknown command: ' + command)
except OSError as kexc:
print('OSError: ' + str(kexc))
parent.handle_disconnect(curr_id)
chan.shutdown(2)
chan.close()
break
time.sleep(1)
def _ssh_listen_for_connections(sock, host_key, parent) -> None:
"""Listens for incoming ssh connections
"""
while 1:
try:
client, _ = sock.accept()
except BaseException as exc:
print('EX: _ssh_listen_for_connections accept ' + str(exc))
break
print('Got a connection!')
chan = None
curr_id = parent.get_next_id()
started = False
try:
t = paramiko.Transport(client)
t.add_server_key(host_key)
paramiko.util.log_to_file("ssh_log.txt")
server = SSHServer()
try:
t.start_server(server=server)
except paramiko.SSHException:
print('SSH negotiation failed')
return
server.parent = parent
chan = t.accept(20)
conn_handler = \
threading.Thread(target=_handle_ssh_connection,
args=(t, chan, parent, server,))
conn_handler.start()
started = True
except EOFError as exc4:
print('EX: _ssh_listen_for_connections EOFError 1 ' + str(exc4))
try:
if started:
parent.handle_disconnect(curr_id)
if chan:
chan.shutdown(2)
chan.close()
except BaseException as exc3:
print('EX: _ssh_listen_for_connections EOFError 2 ' +
str(exc3))
pass
continue
except OSError as exc2:
print("Exit: " + str(exc2))
try:
if started:
parent.handle_disconnect(curr_id)
if chan:
chan.shutdown(2)
chan.close()
except BaseException as exc3:
print('EX: _ssh_listen_for_connections OSError ' + str(exc3))
pass
break
time.sleep(3)
def run_ssh_server(domain: str, ssh_port: int, parent) -> None:
"""Runs an ssh server
"""
host_key_filename = './.ssh_rsa_mud'
host_key = None
try:
host_key = paramiko.RSAKey(filename=host_key_filename)
except FileNotFoundError:
print('Generating SSH server host key')
if not host_key:
host_key = paramiko.RSAKey.generate(bits=2048)
host_key.write_private_key_file(host_key_filename)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((domain, ssh_port))
sock.listen(100)
print('SSH server created on port ' + str(ssh_port))
except BaseException as exc:
print('*** SSH server creation failed: ' + str(exc))
return None
conn_listener = \
threading.Thread(target=_ssh_listen_for_connections,
args=(sock, host_key, parent,))
conn_listener.start()