-
Notifications
You must be signed in to change notification settings - Fork 0
/
setupssh.py
354 lines (317 loc) · 10 KB
/
setupssh.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# Rustyssh
# 12/21/2022, San
# setup ssh keys
import os
import paramiko
import logging
import subprocess
import re
import time
from enum import Enum
import platform
is_win = platform.system() == 'Windows'
if is_win:
import shlex
logger = logging.getLogger('rustyssh')
logging.getLogger("paramiko.transport").setLevel(logging.DEBUG)
DIR = os.path.dirname(os.path.realpath(__file__))
class ReturnBox():
def __init__(self, out='', err=''):
self.output = out
self.error = err
self.drive_status = None
self.returncode = ReturnCode.NONE
self.object = None
class ReturnCode(Enum):
OK = 0
BAD_DRIVE = 1
BAD_HOST = 2
BAD_LOGIN = 3
BAD_SSH = 4
BAD_MOUNT = 5
BAD_WINFSP = 6
NONE = -1
def run(cmd, capture=False, detach=False, shell=True, timeout=30):
cmd = re.sub(r'[\n\r\t ]+',' ', cmd).replace(' ',' ').strip()
header = 'CMD'
if shell:
header += ' (SHELL)'
logger.debug(f'{header}: {cmd}')
r = subprocess.CompletedProcess(cmd, 0)
r.stdout = ''
r.stderr = ''
try:
if detach:
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
p = subprocess.Popen(shlex.split(cmd), close_fds=True,
creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
logger.debug(f'Detached process {p.pid} started.')
else:
r = subprocess.run(cmd, capture_output=capture, shell=shell,
timeout=timeout, text=True)
except Exception as ex:
r.stderr = repr(ex)
logger.error(r)
return r
if r.returncode != 0:
if r.stderr and r.stderr.startswith('Warning'):
logger.warning(r)
else:
logger.error(r)
# else:
# logger.debug(r)
if capture:
r.stdout = r.stdout.strip()
r.stderr = r.stderr.strip()
return r
def get_app_key(user):
if is_win:
return f'{ os.path.expandvars("%USERPROFILE%") }\\.ssh\\id_rsa'
else:
return f'{ os.path.expandvars("$HOME") }/.ssh/id_rsa'
def testhost(userhost, port=22):
'''
Test if host respond to port
Return: True or False
'''
logger.debug(f'Testing port {port} at {userhost}...')
user, host = userhost.split('@')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
rb = ReturnBox()
try:
client.connect(hostname=host, username=user, password='', port=port, timeout=5)
rb.returncode = ReturnCode.OK
except (paramiko.ssh_exception.AuthenticationException,
paramiko.ssh_exception.BadAuthenticationType,
paramiko.ssh_exception.PasswordRequiredException):
rb.returncode = ReturnCode.OK
except Exception as ex:
rb.returncode = ReturnCode.BAD_HOST
rb.error = str(ex)
finally:
client.close()
return rb
def testssh(userhost, port=22):
'''
Test ssh key authentication
'''
user, host = userhost.split('@')
seckey = get_app_key(user)
logger.debug(f'Testing ssh keys for {userhost} using key {seckey}...')
rb = testhost(userhost, port)
if rb.returncode == ReturnCode.BAD_HOST:
return rb
if not os.path.exists(seckey):
if is_win:
seckey = seckey.replace('/','\\')
logger.error(f'Key does not exist: {seckey}')
rb.returncode = ReturnCode.BAD_LOGIN
rb.error = "No key"
return rb
logger.debug(f'Logging in with keys for {userhost}...')
rb = ReturnBox()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
k = paramiko.RSAKey.from_private_key_file(seckey)
try:
client.connect(hostname=host, username=user, port=port, timeout=10, pkey=k)
rb.returncode = ReturnCode.OK
except (paramiko.ssh_exception.AuthenticationException,
paramiko.ssh_exception.BadAuthenticationType,
paramiko.ssh_exception.PasswordRequiredException) as ex:
rb.returncode = ReturnCode.BAD_LOGIN
rb.error = str(ex)
except Exception as ex:
rb.returncode = ReturnCode.BAD_HOST
rb.error = str(ex)
finally:
client.close()
return rb
def generate_keys(userhost):
logger.debug('Generating new ssh keys...')
user, host = userhost.split('@')
seckey = get_app_key(user)
pubkey = f'{seckey}.pub'
now = time.time()
if os.path.exists(seckey):
os.rename(seckey, f'{seckey}.{ now }.bak')
if os.path.exists(pubkey):
os.rename(pubkey, f'{pubkey}.{ now }.bak')
rb = ReturnBox()
# use ssh-keygen
# print(run('where ssh-keygen'))
# cmd = f'echo y |ssh-keygen -q -N "" -f {seckey} -b 2048 -t rsa -m PEM'
# ssh-keygen defaults to openssh rsa 3072 bits keys
# PEM format not supported by libssh2 openssl no-stdio ?
if is_win:
cmd = f'echo y | ssh-keygen -m PEM -q -N "" -f {seckey}'
else:
cmd = f'ssh-keygen -m PEM -q -N "" -f {seckey}'
run(cmd)
with open(pubkey) as r:
pubkey = r.read()
# use paramiko
# sk = paramiko.RSAKey.generate(2048)
# try:
# sshdir = os.path.dirname(seckey)
# if not os.path.exists(sshdir):
# os.makedirs(sshdir)
# os.chmod(sshdir, 0o700)
# sk.write_private_key_file(seckey)
# except Exception as ex:
# logger.error(f'{ex}, {seckey}')
# rb.error = str(ex)
# return rb
# pubkey = f'ssh-rsa {sk.get_base64()} {userhost}'
# try:
# with open(seckey + '.pub', 'wt') as w:
# w.write(pubkey)
# except Exception as ex:
# msg = f'Could not save public key: {ex}'
# logger.error(msg)
# rb.error = msg
# return rb
rb.output = pubkey
return rb
def has_app_keys(user):
logger.debug('checking if user has keys...')
seckey = get_app_key(user)
pubkey = f'{seckey}.pub'
output = ''
if os.path.exists(seckey):
try:
sk = paramiko.RSAKey.from_private_key_file(seckey)
output = f'ssh-rsa {sk.get_base64()}'
if os.path.exists(pubkey):
with open(pubkey) as r:
output2 = r.read()
if output.split()[1] != output2.split()[1]:
logger.error('public key invalid!!!!!!!!!!!!!')
logger.error(output)
logger.error(output2)
output = ''
logger.debug('current keys are ok')
except Exception as ex:
logger.error(ex)
return output and output.startswith('ssh-rsa')
def set_key_permissions(user):
logger.debug('setting ssh key permissions...')
seckey = get_app_key(user)
ssh_folder = os.path.dirname(seckey)
run(fr'icacls {seckey} /c /t /inheritance:d', capture=True)
run(fr'icacls {seckey} /c /t /grant { os.environ["USERNAME"] }:F', capture=True)
run(fr'icacls {seckey} /c /t /grant SYSTEM:F', capture=True)
run(fr'icacls {seckey} /c /t /remove Administrator BUILTIN\Administrators BUILTIN Everyone Users', capture=True)
# Verify
# run(fr'icacls {seckey}')
def main(userhost, password, port=22):
'''Setup ssh keys, return ReturnBox'''
logger.debug(f'Setting up ssh keys for {userhost}...')
rb = ReturnBox()
user, host = userhost.split('@')
seckey = get_app_key(user)
pubkey = ''
if has_app_keys(user):
logger.debug('Private key already exists.')
sk = paramiko.RSAKey.from_private_key_file(seckey)
pubkey = f'ssh-rsa {sk.get_base64()} {userhost}'
else:
rbkey = generate_keys(userhost)
if rbkey.error:
rbkey.returncode = ReturnCode.BAD_SSH
return rbkey
else:
pubkey = rbkey.output
# connect
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
rb.error = ''
try:
logger.debug('Connecting using password...')
client.connect(hostname=host, username=user, password=password, port=port, timeout=10, look_for_keys=False)
except paramiko.ssh_exception.AuthenticationException as ex:
rb.error = f'User or password wrong'
rb.error += f'\nUser: {user}'
rb.error += f'\nPass: {password}'
rb.error += f'\nHost: {host}'
rb.error += f'\nPort: {port}'
rb.error += f'\nerror: {ex}'
rb.returncode = 1
except Exception as ex:
rb.error = f'connection error: {ex}'
rb.returncode = 2
if rb.error:
logger.error(rb.error)
if 'getaddrinfo failed' in rb.error:
rb.error = f'{host} not found'
client.close()
rb.returncode = ReturnCode.BAD_SSH
return rb
if is_win:
set_key_permissions(user)
logger.debug(f'Publising public key...')
# Copy to the target machines.
# cmd = f"exec bash -c \"cd; umask 077; mkdir -p .ssh && echo '{pubkey}' >> .ssh/authorized_keys || exit 1\" || exit 1"
cmd = f"exec sh -c \"cd; umask 077; mkdir -p .ssh; echo '{pubkey}' >> .ssh/authorized_keys\""
logger.debug(cmd)
ok = False
try:
stdin, stdout, stderr = client.exec_command(cmd, timeout=10)
rc = stdout.channel.recv_exit_status()
if rc == 0:
logger.debug('Key transfer successful')
rb.returncode = ReturnCode.OK
else:
logger.error(f'Error transfering public key: exit {rc}, error: {stderr}')
except Exception as ex:
logger.error(ex)
rb.returncode = ReturnCode.BAD_SSH
rb.error = f'error transfering public key: {ex}'
return rb
finally:
client.close()
err = stderr.read()
if err:
logger.error(err)
rb.returncode = ReturnCode.BAD_SSH
rb.error = f'error transfering public key, error: {err}'
return rb
rb = testssh(userhost, port)
if rb.returncode == ReturnCode.OK:
rb.output = "SSH setup successfull."
logger.info(rb.output)
else:
message = 'SSH setup test failed'
detail = ''
if rb.returncode == ReturnCode.BAD_LOGIN:
detail = ': authentication probem'
else:
message = ': connection problem'
rb.error = message
rb.returncode = ReturnCode.BAD_SSH
logger.error(message + detail)
return rb
if __name__ == '__main__':
import sys
import os
import getpass
assert (len(sys.argv) > 2 and '@' in sys.argv[1]) # usage: prog user@host pass
platform = 'x64'
if 'PLATFORM' in os.environ:
platform = os.environ['PLATFORM']
path = os.environ['PATH']
os.environ['PATH'] = f'{DIR};{DIR}\\..\\vendor\\{platform}\\openssh;{path}'
userhost = sys.argv[1]
password = sys.argv[2]
port=22
if ':' in userhost:
userhost, port = userhost.split(':')
logging.basicConfig(level=logging.DEBUG)
# logging.basicConfig(level=logging.DEBUG)
user, host = userhost.split('@')
if has_app_keys(user) and testssh(userhost, port).returncode == ReturnCode.OK:
logger.info('SSH authentication is OK, no need to setup.')
else:
main(userhost, password, port)