forked from realvnc-labs/rport-e2e-tests
-
Notifications
You must be signed in to change notification settings - Fork 2
/
totp2fa.py
executable file
·373 lines (311 loc) · 13.6 KB
/
totp2fa.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import os
import sys
import logging.config
import argparse
import time
from configparser import ConfigParser
import pyotp
import paramiko
import requests
from requests.auth import HTTPBasicAuth
from api_scaleway import ApiScaleway
from api_godaddy import ApiGoDaddy
from helper import Helper
LOGGING_CONFIG = {
'formatters': {
'brief': {
'format': '[%(asctime)s][%(levelname)s] %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'brief'
},
'rotating_file_handler': {
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'brief',
'filename': 'e2e.log',
'maxBytes': 1024*1024,
'backupCount': 1,
}
},
'loggers': {
'main': {
'propagate': False,
'handlers': ['console', 'rotating_file_handler'],
'level': 'INFO'
}
},
'version': 1
}
SSH_PATH = os.getenv("SSH_PATH")
AUTH_INSTALLER = os.getenv("AUTH_INSTALLER")
SSH_PWD = os.getenv("SSH_PWD")
PAIRING_URL = "https://pairing.rport.io/"
CWD = os.path.dirname(os.path.realpath(__file__))
CONFIG_PATH = os.path.join(CWD, "rport.cfg")
class Master:
"""
Executes various API tests on rport
having tot2fa enabled
and returns a test summary
"""
def __init__(self, logger, args_in):
self.logger = logger
self.args = args_in
# store script results for summary
self.summary = {
'log-in': "undefined",
'failures': []
}
def process(self):
"""
Creates a server on scaleway with totp2fa
Runs various API tests and returns a summary
"""
server_id = None
rport_details = None
secret = None
ip_address = None
scaleway = ApiScaleway(self.logger)
parser_conf = ConfigParser()
godaddy = ApiGoDaddy(self.logger)
parser_conf.read(CONFIG_PATH)
try:
# -----------------------------------------------------------
# ++++ create server on scaleway
# -----------------------------------------------------------
server = scaleway.create_server()
ip_address = server['server']['public_ip']['address']
server_id = server['server']['id']
ssh_client = paramiko.SSHClient()
my_pkey = paramiko.RSAKey.from_private_key_file(SSH_PATH, password=SSH_PWD)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.logger.info("Connecting to: %s", ip_address)
err = "error not provided!"
for _ in range(90):
try:
ssh_client.connect(hostname=ip_address, username="root", pkey=my_pkey)
sys.stdout.write("ok\n")
sys.stdout.flush()
break
except Exception:
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(1)
else:
self.logger.error("Couldn't connect to the SSH Server: %s", err)
raise Exception("Couldn't connect to the SSH Server: %s" % err)
self.logger.info("Connected to: %s", ip_address)
# download rport server installer
command = "apt-get update --allow-releaseinfo-change"
self.exec_command(ssh_client, command)
if self.args.auth_installer:
command = "curl -u %s -o installer.sh https://get.rport.io &&" \
" bash installer.sh -h" % AUTH_INSTALLER
else:
command = "curl -o installer.sh https://get.rport.io &&" \
" bash installer.sh -h"
self.exec_command(ssh_client, command)
# install rport server
if self.args.unstable:
command = "bash installer.sh -t -o"
else:
command = "bash installer.sh -o"
out = self.exec_command(ssh_client, command)
# get server details: url, user and password
helper = Helper(self.logger)
rport_details = helper.get_match_from_output(out)
# get rportd version
command = "rportd --version"
self.summary['version'] = self.exec_command(ssh_client, command).strip("\n")
# -----------------------------------------------------------
# ++++ login
# GET {{rporturl}}/api/v1/login
# POST {{rporturl}}/api/v1/me/totp-secret
# POST {{rporturl}}/api/v1/verify-2fa
# -----------------------------------------------------------
r_login = requests.get(rport_details['url'] + "/api/v1/login",
auth=HTTPBasicAuth(rport_details['user'],
rport_details['password']))
login = r_login.json()
self.summary['log-in'] = self.has_no_errors(login)
# read secret key
auth_header = {"Authorization": "Bearer " + login["data"]["token"]}
secret = requests.post(rport_details['url'] + "/api/v1/me/totp-secret",
headers=auth_header).json()
self.has_no_errors(secret)
# verify totp 2fa
totp = pyotp.TOTP(secret['secret'])
payload = {"username": "admin", "token": totp.now()}
r_verify = requests.post(rport_details['url'] + "/api/v1/verify-2fa",
json=payload,
headers=auth_header)
verify = r_verify.json()
self.summary['log-in'] = self.has_no_errors(verify)
# -----------------------------------------------------------
# ++++ create a script
# to make sure totp token works
# -----------------------------------------------------------
payload = {
"name": "current_directory",
"interpreter": "cmd",
"is_sudo": True,
"cwd": "/home",
"script": "pwd"
}
auth_header = {"Authorization": "Bearer " + verify["data"]["token"]}
create_script = requests.post(rport_details['url'] + "/api/v1/library/scripts",
json=payload,
headers=auth_header).json()
self.summary['create-script'] = self.has_no_errors(create_script)
if create_script['data']['name'] != "current_directory":
self.logger.error("create script: %s", create_script['data'])
raise Exception("create script failed")
# -----------------------------------------------------------
# ++++ status
# -----------------------------------------------------------
status = requests.get(rport_details['url'] + "/api/v1/status",
headers=auth_header).json()
self.has_no_errors(status)
if status['data']['two_fa_delivery_method'] != 'totp_authenticator_app':
self.logger.error("create script: %s", status)
raise Exception("status failed")
except Exception as error:
self.logger.error("Test failed with the following error: %s", error)
self.summary['failures'].append(error)
raise
finally:
if not self.summary['failures']:
self.logger.debug("--------- Details --------------")
self.logger.debug("TOTP secret: %s", secret['secret'])
self.logger.debug("totp = pyotp.TOTP('%s')", secret['secret'])
self.logger.debug("Public server IP: %s", ip_address)
self.logger.debug("Rport server url: %s", rport_details['url'])
self.logger.debug("User and password: %s, %s", rport_details['user'],
rport_details['password'])
self.logger.debug("-----------------------------------")
# -----------------------------------------------------------
# ++++ Tear down server
# -----------------------------------------------------------
# delete scaleway server
if server_id:
delete = scaleway.delete_server(server_id)
if delete is not None:
self.summary['failures'].append(delete)
# delete godaddy record
if rport_details.get('record'):
godaddy.delete_record(rport_details['record']) # format: '30xmycbinf42.users'
# -----------------------------------------------------------
# ++++ Summary
# -----------------------------------------------------------
self.logger.info("-----------------------------------")
self.logger.info("--------- Summary ---------------")
self.logger.info("-----------------------------------")
self.logger.info("Rport server version: %s", self.summary['version'])
self.logger.info("API log in admin: %s", self.summary['log-in'])
self.logger.info("-----------------------------------")
if self.summary['failures']:
self.logger.info("--------- Failures --------------")
self.logger.info("-----------------------------------")
self.logger.info("--------- Total (%d) ------------",
len(self.summary['failures']))
for failure in self.summary['failures']:
self.logger.error(failure)
self.logger.info("-----------------------------------")
raise Exception("Failures reported.")
self.logger.info("No summary errors reported.")
def exec_command(self, client, command):
"""
executes commands on the rport server
:param client:
:param command:
:return: stdout of the command executed
"""
self.logger.info("Execute server command: %s. Be patient!", command)
for _ in range(3):
_, stdout, stderr = client.exec_command(command)
err = stderr.read().decode()
out = stdout.read().decode()
exit_status = stdout.channel.recv_exit_status()
if exit_status != 0:
self.logger.error(err)
else:
self.logger.info("Server command executed ok: %s" % command)
break
else:
self.logger.error("Execute mandatory server command: %s failed!", command)
raise Exception("Execute mandatory server command failed. See logs for details")
self.logger.info(out)
return out
def exec_instance_command(self, instance, command):
"""
Executes a command on an instance
:param instance: instance object
:param command: command to execute
:return
"""
stderr = None
for _ in range(3):
(exit_code, stdout, stderr) = instance.execute(command)
if exit_code != 0:
self.logger.warning("stderr: %s", stderr)
self.logger.warning("stdout: %s", stdout)
self.logger.info("Something went wrong while exec: %s Don't you worry,"
" we re-try up to 3 attempts",
command)
time.sleep(3)
else:
self.logger.info("Instance command executed ok: %s" % command)
if stdout:
self.logger.info(stdout)
return stdout
self.logger.error("Instance command failed: %s" % command)
self.summary['failures'].append(stderr)
return stderr
def has_no_errors(self, response):
"""
Checks if response has any errors
:param response: response object
:return:
"""
if response.get("errors"):
self.logger.error("Request exited with errors: %s", response)
self.summary['failures'].append(response)
return response
self.logger.info("Request ok: %s", response)
return "ok"
def wait_for_instance_state(self, instance, state):
"""
Waits until an instance has the required state
:param instance: instance object
:param state: required state
:return:
"""
self.logger.info("Wait for instance status: %s", state)
for _ in range(60):
self.logger.debug(instance.state().status)
if instance.state().status == state:
return
time.sleep(5)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='rport-e2e')
parser.add_argument('--logger', action="store", dest="logger", default="INFO")
parser.add_argument('--unstable', action="store_true", dest="unstable")
parser.add_argument('--auth-installer', action="store_true",
dest="auth_installer", default=True)
args = parser.parse_args()
print("[INFO] Logger: {}".format(args.logger))
if args.unstable:
print("[INFO] Running unstable release")
else:
print("[INFO] Running stable release")
if args.auth_installer:
print("[INFO] Server installer authenticated. Let's encrypt is not used.")
logging.config.dictConfig(LOGGING_CONFIG)
log = logging.getLogger('main')
log.setLevel(level=logging.getLevelName(args.logger))
master = Master(log, args)
master.process()