-
Notifications
You must be signed in to change notification settings - Fork 0
/
csctester3.py
executable file
·2142 lines (1972 loc) · 98.3 KB
/
csctester3.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import pudb; pu.db
from collections import OrderedDict
from logging.handlers import TimedRotatingFileHandler
from operator import itemgetter
import base64
import click
import copy
import curses
import curses.textpad as textpad
import getpass
import json
import logging
import os
import re
import requests
import shutil
import signal
import sys
import tempfile
import traceback
__author__ = 'Davide Barelli'
__version__ = '2.1.1'
__user__ = [ 'Davide', 'Barelli' ]
'''
TODO List
=========
* set default PIN by regex
* send OTP only when requested
BUGS
* exit with value 1 if no signature has been performed with check command (even without errors, e.g. invalid credentials)
* show message for quitting TUI
'''
class GlobalAttributes:
pass
_priv_attr = GlobalAttributes()
_priv_attr.colorize = True
def get_logger(log_file_name=None):
global _priv_attr
logger = logging.getLogger(__name__)
if log_file_name:
handler = TimedRotatingFileHandler(log_file_name, when='midnight', interval=1, backupCount=15, encoding='utf-8')
handler.suffix = '%Y-%m-%d.log'
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
_priv_attr.colorize = False
logger.setLevel(logging.INFO)
else:
handler = logging.StreamHandler(sys.stdout)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
return logger
def logger_style_artist(func):
def wrapper(*args, **kwargs):
global _priv_attr
# do not colorize output when logging to a file
return func(*args, **kwargs) if _priv_attr.colorize else args[0]
return wrapper
class CSCCursesMenu(object):
DEFAULT_CREDENTIALS_FILE_NAME = 'csccredentials.json'
def __init__(self, config_file_name):
self.running = True
os.system('clear')
self.screen = curses.initscr()
self.screen.keypad(1) # enable keyboard numpad
# init curses and curses input
curses.noecho() # disable the keypress echo to prevent double input
curses.cbreak() # disable line buffers to run the keypress immediately
curses.start_color()
curses.curs_set(0) # hide cursor
# set up color pair
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_CYAN)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(4, 33, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
self.hilite_color = curses.color_pair(1)
self.title_color = curses.color_pair(2)
self.status_bar_color = curses.color_pair(3)
self.blue_color = curses.color_pair(4)
self.red_color = curses.color_pair(5)
self.cyan_color = curses.color_pair(6)
self.normal_color = curses.A_NORMAL
self.menu = {
'environment': {
'subtitle': 'Choose an environment'
# parent: exit
},
'virtual_host': {
'subtitle': 'Choose a virtual host',
'parent': 'environment'
},
'users': {
'subtitle': 'Choose a user',
'parent': 'virtual_host'
},
'cache': {
'subtitle': None
# parent: exit
}
}
self._load_environment_menu()
signal.signal(signal.SIGINT, self._sig_handler)
self.script_dir = os.path.dirname(os.path.realpath(__file__))
self.config_file_path = f'{self.script_dir}/{config_file_name}'
try:
f = open(self.config_file_path, 'r')
except Exception:
self.conf_file = False
self.users_data = {}
else:
self.conf_file = True
with f:
self.users_data = json.load(f)
def _sig_handler(self, signal, frame):
self.destroy()
print(CSC.highlight('CSC tester terminated', 'DeepPink1', bold=True), file=sys.stderr)
sys.exit(1)
def _prompt_selection(self, parent=None):
sub_menu = self.menu['selected']
if not parent:
if 'parent' in self.menu[sub_menu]:
back_option = f'Return to previous menu ({self.menu[sub_menu]["parent"].title()})'
else:
back_option = None
else:
back_option = f'Return to previous menu ({parent["title"]})'
exit_option = "Exit"
option_count = len(self.menu[sub_menu]['options'])
list_count = option_count + (0 if not back_option else 1) # considering back option
input_key = None
# keys mapping
back_keys = [curses.KEY_LEFT, ord('B'), ord('b')]
down_keys = [curses.KEY_DOWN, ord('J'), ord('j')]
enter_keys = [curses.KEY_RIGHT, ord('\n')]
exit_keys = [ord('Q'), ord('q')]
help_keys = [ord('H'), ord('h')]
up_keys = [curses.KEY_UP, ord('K'), ord('k')]
self.selected_option = 0
while input_key not in enter_keys:
# self.screen.clear()
self.screen.erase()
self.screen.border(0)
self._draw_title()
self._draw_status_bar("Press 'h' for help")
list(map(lambda o: self._draw_option(o, self.hilite_color if self.selected_option == o else self.normal_color), range(option_count)))
self.screen.addstr(self.curr_ord + option_count + 1, 4, f'{exit_option if not back_option else back_option}', self.hilite_color if self.selected_option == option_count else self.normal_color)
if back_option is not None:
color = self.hilite_color if self.selected_option == option_count + 1 else self.normal_color
self.screen.addstr(self.curr_ord + option_count + 2, 4, f'{exit_option}', color)
self.screen.refresh()
input_key = self.screen.getch()
if input_key in down_keys:
if self.selected_option < list_count:
self.selected_option += 1
else:
self.selected_option = 0
if input_key in up_keys:
if self.selected_option > 0:
self.selected_option -= 1
else:
self.selected_option = list_count
if input_key in back_keys and back_option is not None:
self.selected_option = list_count - 1 # auto select back and return
break
if input_key in help_keys:
self._help_scr()
if input_key in exit_keys:
self.selected_option = list_count # auto select exit and return
break
return self.selected_option
def _draw_option(self, option_number, style):
sub_menu = self.menu['selected']
self.screen.addstr(self.curr_ord + option_number,
4,
f'{self.menu[sub_menu]["options"][option_number]["title"]}',
style)
def _draw_title(self, subtitle=None):
self.screen.attron(curses.A_UNDERLINE)
self.screen.attron(curses.A_BOLD)
self.screen.attron(self.title_color)
if not self._draw_title_enhanched():
self.screen.addstr(2, 2, 'CSC Tester')
self.curr_ord = 4
self.screen.attroff(curses.A_UNDERLINE)
self.screen.attroff(curses.A_BOLD)
self.screen.attroff(self.title_color)
if subtitle is None:
sub_menu = self.menu['selected']
if 'subtitle' in self.menu[sub_menu]:
if isinstance(self.menu[sub_menu]['subtitle'], list):
subtitle = self.menu[sub_menu]['subtitle']
elif isinstance(self.menu[sub_menu]['subtitle'], dict):
subtitle = [ self.menu[sub_menu]['subtitle'] ]
elif isinstance(self.menu[sub_menu]['subtitle'], str):
subtitle = [{
'text': self.menu[sub_menu]['subtitle'],
'style': [ curses.A_BOLD ]
}]
else:
return
else:
return
elif isinstance(subtitle, dict):
subtitle = [ subtitle ]
elif isinstance(subtitle, str):
subtitle = [{
'text': subtitle,
'style': [ curses.A_BOLD ]
}]
else:
return
for row in subtitle:
list(map(lambda x: self.screen.attron(x), row['style'] if 'style' in row else []))
self.screen.addstr(self.curr_ord, 2, row['text'])
list(map(lambda x: self.screen.attroff(x), row['style'] if 'style' in row else []))
self.curr_ord += 1 if len(subtitle) > 1 else 0
self.curr_ord += 1
def _draw_title_enhanched(self):
max_y, max_x = self.screen.getmaxyx()
left_indent = 3
if max_x < 43 + left_indent + 1:
return False
self.screen.attroff(curses.A_UNDERLINE)
self.screen.addstr(1, left_indent, ' _ _ ')
self.screen.addstr(2, left_indent, ' | | | | ')
self.screen.addstr(3, left_indent, ' ___ ___ ___ | |_ ___ ___| |_ ___ _ __ ')
self.screen.addstr(4, left_indent, ' / __/ __|/ __| | __/ _ \/ __| __/ _ \ \'__|')
self.screen.addstr(5, left_indent, '| (__\__ \ (__ | || __/\__ \ || __/ | ')
self.screen.addstr(6, left_indent, ' \___|___/\___| \__\___||___/\__\___|_| ')
self.curr_ord = 8
return True
def _load_environment_menu(self):
self.menu['selected'] = 'environment'
sub_menu = self.menu['environment']
sub_menu['options'] = [ { 'title': e.title(), 'value': e } for e in CSC.env_IDs ]
self.environment_name = None
self.v_host_ctx_path = None
def _load_virtual_host_menu(self):
self.menu['selected'] = 'virtual_host'
sub_menu = self.menu['virtual_host']
sub_menu['options'] = [ { 'title': v.title(), 'value': v } for v in CSC.virtual_host if self.environment_name in CSC.virtual_host[v] ]
self.v_host_ctx_path = None
def _load_users_menu(self):
self.menu['selected'] = 'users'
sub_menu = self.menu['users']
sub_menu['options'] = []
self.curr_users = {}
for u in self.users_data:
env_allowed_list = self.users_data[u]['environment']
for e in env_allowed_list:
if 'name' in e and self.environment_name in e['name']:
self.curr_users[u] = e['password'] if 'password' in e else 'password'
sub_menu['options'].append({
'title': u,
'value': u
})
break
sub_menu['options'] = sorted(sub_menu['options'], key=itemgetter('title'))
sub_menu['options'].append({
'title': 'Existing Session-Key',
'value': 'sessionkey'
})
sub_menu['options'].append({
'title': 'Create a user',
'value': 'new'
})
def _user_cache_management(self):
if 'cache' not in self.users_data:
return False
self.menu['selected'] = 'cache'
cache = self.users_data['cache']
sub_menu = self.menu['cache']
sub_menu['options'] = [
{
'title': 'yes',
'value': 'y'
},
{
'title': 'no',
'value': 'n'
}
]
sub_menu['subtitle'] = [
{
'text': 'Use last configuration?',
'style': [ curses.A_BOLD ]
},
{
'text': f'{cache["username"]} \u2192 {[ k for k, v in CSC.env_URLs.items() if v == cache["ctx_path"] ][0]}',
'style': [
curses.A_BOLD,
self.blue_color
]
}
]
selected_option = self._prompt_selection()
if selected_option is len(sub_menu['options']):
return None
use_cache = sub_menu['options'][selected_option]['value'] == 'y'
if use_cache:
self.environment_name = cache['environment']
self.v_host_ctx_path = cache['ctx_path']
self.username = cache['username']
self.password = cache['password']
return use_cache
def _help_scr(self):
self.screen.clear()
self.screen.border(0)
_, max_x = self.screen.getmaxyx()
self.screen.attron(curses.A_BOLD)
self.screen.attron(self.red_color)
self.screen.addstr(1, 2, 'CSC Tester ' + __version__ + ' - 2018 ' + __author__)
self.screen.attroff(self.red_color)
self.screen.attron(self.cyan_color)
self.screen.addstr(4, 2, '{:>18}'.format('J j DOWN_ARROW:'))
self.screen.addstr(5, 2, '{:>18}'.format('K k UP_ARROW:'))
self.screen.addstr(6, 2, '{:>18}'.format('ENTER RIGHT_ARROW:'))
self.screen.addstr(7, 2, '{:>18}'.format('B b LEFT_ARROW:'))
self.screen.addstr(8, 2, '{:>18}'.format('Q q:'))
self.screen.addstr(9, 2, '{:>18}'.format('H h:'))
self.screen.attroff(self.cyan_color)
self.screen.addstr(4, 21, 'down')
self.screen.addstr(5, 21, 'up')
self.screen.addstr(6, 21, 'select option')
self.screen.addstr(7, 21, 'back')
self.screen.addstr(8, 21, 'quit')
self.screen.addstr(9, 21, 'display help')
self.screen.attroff(curses.A_BOLD)
self._draw_status_bar('press any key to go back')
self.screen.getch()
def display(self):
self.username = self.password = session_key = None
use_cache = self._user_cache_management()
if use_cache is None:
self.destroy()
return None
while not use_cache:
if not self.environment_name:
# environment
self._load_environment_menu()
sub_menu = self.menu['environment']
selected_option = self._prompt_selection()
if selected_option is len(sub_menu['options']):
self.destroy()
return None
env = sub_menu['options'][selected_option]
self.environment_name = env['value']
elif not self.v_host_ctx_path:
# virtual host
self._load_virtual_host_menu()
sub_menu = self.menu['virtual_host']
selected_option = self._prompt_selection()
if selected_option is len(sub_menu['options']):
# back
self.environment_name = None
continue
elif selected_option is len(sub_menu['options']) + 1:
self.destroy()
return None
v_host = sub_menu['options'][selected_option]
self.v_host_ctx_path = CSC.virtual_host[v_host['value']][self.environment_name]
else:
# user
sub_menu = self.menu['users']
self._load_users_menu()
selected_option = self._prompt_selection()
if selected_option is len(sub_menu['options']):
# back
self.v_host_ctx_path = None
continue
elif selected_option is len(sub_menu['options']) + 1:
self.destroy()
return None
elif sub_menu['options'][selected_option]['value'] == 'sessionkey':
session_key = self._get_string('Session Key:')
if not session_key:
continue
break
elif sub_menu['options'][selected_option]['value'] == 'new':
while True:
username = self._get_string('Username:')
if not username:
break
password = self._get_string('Password:')
if password:
break
if not username or not password:
username = password = None
continue
elif self._create_user(username, password):
break
continue
self.username = sub_menu['options'][selected_option]['value']
if self.username is not None:
self.password = self.curr_users[self.username]
# TODO no user available
break
self.destroy()
ret = {
'environment': self.environment_name,
'ctx_path': self.v_host_ctx_path,
'username': self.username,
'password': self.password
}
if self.username and not use_cache:
# save last data used
self.users_data['cache'] = ret
self._update_config_file()
ret['session_key'] = session_key
return ret
def _create_user(self, username, password):
self.username = username
self.password = password
if username == 'cache':
# TODO invalid username 'cache'
return False
if username not in self.users_data:
self.users_data[username] = {
'environment': [{
'name': [
self.environment_name
],
'password': password
}]
}
else:
user = self.users_data[username]
if 'environment' not in user:
user['environment'] = []
for e in user['environment']:
if 'name' in e and self.environment_name in e['name']:
# clean old declarations
if 'password' in e and password != e['password']:
e['name'].remove(self.environment_name)
elif 'password' not in e and password != 'password':
e['name'].remove(self.environment_name)
else:
# configuration already present
return True
if len(e['name']) is 0:
user['environment'].remove(e)
for e in user['environment']:
if 'password' in e and password == e['password'] or 'password' not in e and password == 'password':
if 'name' not in e:
e['name'] = []
if self.environment_name not in e['name']:
e['name'].append(self.environment_name)
return True
user['environment'].append({
'name': [
self.environment_name
],
'password': password
})
return True
def _update_config_file(self, content=None):
if content is None:
content = self.users_data
if self.conf_file:
tmp_backup_file = f'{tempfile.gettempdir()}/{next(tempfile._get_candidate_names())}'
try:
shutil.copy(self.config_file_path, tmp_backup_file)
except Exception as e:
print('{} {}'.format(CSC.highlight('An error occurred while creating a backup file', 'red', bold=True), e), file=sys.stderr)
return False
try:
open(self.config_file_path, 'w').close()
with open(self.config_file_path, 'w') as f:
f.write(json.dumps(content, indent=4, sort_keys=True))
except Exception as e:
print('{} {}'.format(CSC.highlight('An error occurred while updating your configuration file', 'yellow'), e), file=sys.stderr)
if self.conf_file:
try:
print(CSC.highlight('Restoring the old configuration', 'yellow'), file=sys.stderr)
shutil.copy(tmp_backup_file, self.config_file_path)
except Exception:
print(CSC.highlight('Cannot restore configuration file, a backup file has been saved in path ' + tmp_backup_file, 'red', bold=True), file=sys.stderr)
return False
os.remove(tmp_backup_file)
return False
if self.conf_file:
os.remove(tmp_backup_file)
return True
def _draw_status_bar(self, message):
max_y, max_x = self.screen.getmaxyx()
if len(message) > max_x - 2:
return False
self.screen.addstr(max_y - 2, 1, f'{message: >{str(max_x - 3)}} ', self.status_bar_color)
return True
def _get_string(self, label, draw_title=True):
self.screen.clear()
if draw_title:
self._draw_title('')
curses.echo()
curses.curs_set(1)
_, max_x = self.screen.getmaxyx()
self.screen.border(0)
indent = max_x // 5 - len(label) if max_x // 5 - len(label) > 0 else 2
curr_ord = self.curr_ord + 2
self.screen.addstr(curr_ord, indent, label, curses.A_BOLD)
self._draw_status_bar('Insert an empty string to go back')
self.screen.refresh()
try:
textpad.rectangle(self.screen, curr_ord - 1, indent + len(label) + 1, curr_ord + 1, max_x - 2) # rectangle(win, uly, ulx, lry, lrx)
val = self.screen.getstr(curr_ord, indent + len(label) + 2, max_x - len(label) - indent - 4) # getstr(begin_y, begin_x, ncols)
return val.decode('utf-8').strip()
except Exception:
return None
finally:
curses.noecho()
curses.curs_set(0)
def destroy(self):
self.running = False
curses.endwin()
class CSC(object):
ALGO_RSA_ENC = '1.2.840.113549.1.1.1'
ALGO_SHA1_WITH_RSA_ENC = '1.2.840.113549.1.1.5'
ALGO_SHA224_WITH_RSA_ENC = '1.2.840.113549.1.1.14'
ALGO_SHA256_WITH_RSA_ENC = '1.2.840.113549.1.1.11'
ALGO_SHA384_WITH_RSA_ENC = '1.2.840.113549.1.1.12'
ALGO_SHA512_WITH_RSA_ENC = '1.2.840.113549.1.1.13'
ALGO_RSASSA_PSS = '1.2.840.113549.1.1.10'
HASH_SHA1_OID = '1.3.14.3.2.26'
HASH_SHA224_OID = '2.16.840.1.101.3.4.2.4'
HASH_SHA256_OID = '2.16.840.1.101.3.4.2.1'
HASH_SHA384_OID = '2.16.840.1.101.3.4.2.2'
HASH_SHA512_OID = '2.16.840.1.101.3.4.2.3'
HASH_SHA1_VALUE = 'A8/XQ2YfB5dfovEiDFGUy6/0hFE=' # echo abc | sha1sum | xxd -r -p | base64 | tr -d '\r\n'
HASH_SHA224_VALUE = '9ck7bwb3xW1+pyDBIeOx+2cw5c9fGNd2vw8tiA==' # echo abc | sha224sum | xxd -r -p | base64 | tr -d '\r\n'
HASH_SHA256_VALUE = '7eqv8/F3StKIhnN3DG1kCX45G8Ni19b7NJgt3w79GMs=' # echo abc | sha256sum | xxd -r -p | base64 | tr -d '\r\n'
HASH_SHA384_VALUE = '6NFCC0/0HD8SGG2JSpnhxKpoHaecRwB+na3s2eywSC7h4iRRDnSEB4wCifNDlrnD' # echo abc | sha384sum | xxd -r -p | base64 | tr -d '\r\n'
HASH_SHA512_VALUE = 'TyhdDAzHcobYcxeYt6riY54oJw1BZvQNdpy73KUjBxTYSEg9Nk4vOf5suQg8FSKbOaM2FevG1XYF98Q/aQZznQ==' # echo abc | sha512sum | xxd -r -p | base64 | tr -d '\r\n'
env_IDs = [
'produzione'
]
virtual_host = OrderedDict([
('time4mind', {
'produzione': 'https://services.time4mind.com/csc/v0'
}),
('bankid-no', {
'produzione': 'https://bnkidno.time4mind.com/csc/v0'
}),
('bankid-se', {
'produzione': 'https://bnkidse.time4mind.com/csc/v0'
}),
('ftn', {
'produzione': 'https://ftn.time4mind.com/csc/v0'
}),
('globalsign', {
'produzione': 'https://globalsign.time4mind.com/csc/v0'
}),
('idin', {
'produzione': 'https://idin.time4mind.com/csc/v0'
}),
('nemid', {
'produzione': 'https://nemid.time4mind.com/csc/v0'
}),
('transsped', {
'transsped (produzione)': 'https://services.cloudsignature.online/csc/v0'
})
])
env_URLs = {
'produzione': 'https://services.time4mind.com/csc/v0'
}
service_logo_URLs = OrderedDict([
('adobe-prod', 'https://services.time4mind.com/res_ext/vendors/adobe/csc_adobe.jpg'),
('bankidse-prod', 'https://services.time4mind.com/res_ext/vendors/bankid/csc_bankid.jpg'),
('bankidno-prod', 'https://services.time4mind.com/res_ext/vendors/bankidno/csc_bankidno.jpg'),
('ftn-prod', 'https://services.time4mind.com/res_ext/vendors/ftn/logo-en.png'),
('globalsign-prod', 'https://services.time4mind.com/res_ext/vendors/globalsign/csc_globalsign.png'),
('idin-prod', 'https://services.time4mind.com/res_ext/vendors/idin/idin_logo.png'),
('intesi-prod-new', 'https://services.time4mind.com/res_ext/logo_IG_symbol.png'),
('nemid-prod', 'https://services.time4mind.com/res_ext/vendors/nemid/csc_nemid.jpg'),
('transsped-prod-new', 'https://services.time4mind.com/res_ext/vendors/transsped/csc_transsped.png')
])
oauth_logo_URLs = OrderedDict([
('bankidse-prod', 'https://services.time4mind.com/res_ext/vendors/bankid/img/oauthLogo.png'),
('bankidno-prod', 'https://services.time4mind.com/res_ext/vendors/bankidno/img/oauthLogo.png'),
('globalsign-prod', 'https://services.time4mind.com/res_ext/vendors/globalsign/img/oauthLogo.png'),
('idin-prod', 'https://services.time4mind.com/res_ext/vendors/idin/img/oauthLogo.png'),
('intesi-prod', 'https://services.time4mind.com/res_ext/faviconX180.png'), # XXX ???
('nemid-prod', 'https://services.time4mind.com/res_ext/vendors/nemid/img/oauthLogo.png'),
('transsped-prod-new', 'https://services.time4mind.com/res_ext/vendors/transsped/img/oauthLogo.png'),
])
@staticmethod
def getinfostr():
return '{}\n{}\n{}\n{}\n{}\n{}\n\n\n'.format(' _ _ ',
' | | | | ',
' ___ ___ ___ | |_ ___ ___| |_ ___ _ __ ',
' / __/ __|/ __| | __/ _ \/ __| __/ _ \ \'__|',
'| (__\__ \ (__ | || __/\__ \ || __/ | ',
' \___|___/\___| \__\___||___/\__\___|_| ') \
+ f'{CSC.highlight("Version:", bold=True)} {__version__}\n' \
+ f'{CSC.highlight("Author:", bold=True)} {__author__}'
def _generic_test(self, cfg):
tests = cfg['tests']
response = []
for i in range(0, len(tests), 1):
t = tests[i]
h = {} if 'headers' not in t else t['headers']
h['Content-Type'] = 'application/json'
if 'input' not in t or t['input'] is None:
r = requests.get(self.service_URLs[cfg['service']], headers=h, verify=False, json=t['input'])
else:
r = requests.post(self.service_URLs[cfg['service']], headers=h, verify=False, json=t['input'])
if r.text is None or str(r.text) == '':
j = {}
else:
try:
j = r.json()
except ValueError:
self.logger.error(f'[ {CSC.highlight("KO", "red", bold=True)} ] {cfg["service"]} {t["name"] if "name" in t else "test " + str(i + 1)}: cannot parse json response')
return [] # TODO should not return??
check = t['exp_result']
def _traverse_json(root, path):
if not isinstance(root, dict) or not isinstance(path, str):
return None
if '>' in path:
for k in path.split('>'):
if k in root:
root = root[k]
else:
return None
return root
return root[path] if path in root else None
def _in_callback():
if 'arg' not in c or c['arg'] is None:
return False
for a in c['arg']:
if not _traverse_json(j, a):
return True
return False
def _not_in_callback():
if 'arg' not in c or c['arg'] is None:
return False
for a in c['arg']:
if _traverse_json(j, a) is not None:
return True
return False
def _equal_callback():
if 'arg' not in c or c['arg'] is None:
return False
for key in c['arg']:
pattern = c['arg'][key]
node = _traverse_json(j, key)
if not node:
return True
if isinstance(pattern, list):
if not isinstance(node, list) or len([ x for x in zip(pattern, node) if x[0] != x[1] ]) > 0:
return True
elif not re.match(pattern, node):
return True
return False
def _not_equal_callback():
if 'arg' not in c or c['arg'] is None:
return False
for key in c['arg']:
if key in j and j[key] == c['arg'][key]:
return True
return False
def _len_lesser_callback():
if 'arg' not in c or c['arg'] is None:
return False
for key in c['arg']:
node = _traverse_json(j, key)
if not isinstance(node, list) or len(node) >= c['arg'][key]:
return True
return False
def _len_eq_callback():
if 'arg' not in c or c['arg'] is None:
return False
for key in c['arg']:
node = _traverse_json(j, key)
if not isinstance(node, list) or len(node) != c['arg'][key]:
return True
return False
def _len_greater_callback():
if 'arg' not in c or c['arg'] is None:
return False
for key in c['arg']:
node = _traverse_json(j, key)
if not isinstance(node, list) or len(node) <= c['arg'][key]:
return True
return False
for c in check:
try:
if {
'in': _in_callback,
'not in': _not_in_callback,
'eq': _equal_callback,
'not eq': _not_equal_callback,
'<': _len_lesser_callback,
'=': _len_eq_callback,
'>': _len_greater_callback
}[c['condition']]():
self._print_KO_msg(cfg['service'], i + 1, t['input'], j, t['name'] if 'name' in t else None, error_level=2 if 'err_level' not in t else t['err_level'])
self.logger.error(f'{CSC.highlight(" Expected result rules:", bold=True)} {CSC.highlight(json.dumps(check, indent=4, sort_keys=True), "IndianRed1")}\n\n')
break
except Exception as e:
self.logger.error(f'{CSC.highlight("Invalid condition check: " + c["condition"], "yellow", bold=True)} - {type(e).__name__} {e}')
traceback.print_exc()
else:
self._print_OK_msg(cfg['service'], i + 1, t['name'] if 'name' in t else None)
response.append(j)
return response
def info_test(self):
r = requests.get(self.service_URLs['info'], verify=False)
j = r.json()
self.logger.info(f'{json.dumps(j, indent=4, sort_keys=True)}')
if 'logo' in j:
# check logo existence
rr = requests.get(j['logo'], allow_redirects=False)
if rr is None:
self.logger.error(f'[ {CSC.highlight("KO", color="red", bold=True)} ] Logo test failed: {CSC.highlight("info response is empty", color="yellow")}')
elif rr.status_code != 200:
self.logger.error(f'[ {CSC.highlight("KO", color="red", bold=True)} ] Logo test failed: {CSC.highlight("status_code " + str(rr.status_code), color="yellow")}')
elif rr.headers['Content-Type'] != 'image/png' and rr.headers['Content-Type'] != 'image/jpeg':
self.logger.error(f'[ {CSC.highlight("KO", color="red", bold=True)} ] Logo test failed: {CSC.highlight("content type " + str(rr.headers["Content-Type"]), color="yellow")}')
else:
self.logger.info(f'[ {CSC.highlight("OK", color="green", bold=True)} ] Logo test')
else:
self.logger.error(CSC.highlight('Logo URL not present', color='yellow', bold=True))
cfg = {
'service': 'info',
'tests': [
{
'name': 'no arguments',
'input': None,
'exp_result': [
{ 'condition': 'not in', 'arg': [ 'error' ] },
{ 'condition': 'eq', 'arg': { 'lang': 'en-US' }, }
]
},
{
'name': 'IT language',
'input': { 'lang': 'it-IT' },
'exp_result': [
{ 'condition': 'not in', 'arg': [ 'error' ] },
{ 'condition': 'eq', 'arg': { 'lang': 'it-IT' }, }
]
}
]
}
self._generic_test(cfg)
def login_test(self):
if self.session_key is not None:
self.logger.info(f'{CSC.highlight("Login disabled. Using configured sessionkey:", bold=True)} {self.session_key}')
return
if self.credential_encoded is None:
self._set_error_level(1)
raise RuntimeError('*** Login credential unavailable ***')
cfg = {
'service': 'auth/login',
'tests': [
{ # 1
'name': 'simple login',
'headers': { 'Authorization': 'Basic ' + self.credential_encoded },
'input': None,
'exp_result': [
{ 'condition': 'in', 'arg': [ 'access_token' ] },
{ 'condition': 'not in', 'arg': [ 'refresh_token', 'error' ] }
]
},
{ # 2
'name': 'remember me login',
'headers': { 'Authorization': 'Basic ' + self.credential_encoded },
'input': { 'rememberMe': True },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'access_token', 'refresh_token' ] },
{ 'condition': 'not in', 'arg': [ 'error' ] }
]
}
]
}
r = self._generic_test(cfg)
self.session_key = None
self.refresh_token = None
found = False
# save access_token/refresh_token and revoke the others
for i in range(len(cfg['tests']) - 1, -1, -1):
if not found and 'error' not in r[i] and 'access_token' in r[i]:
self.session_key = r[i]['access_token']
if 'refresh_token' in r[i]:
self.refresh_token = r[i]['refresh_token']
found = True
elif 'access_token' in r[i]:
self.single_revoke(r[i]['access_token'])
if self.session_key is None:
self._set_error_level(1)
raise RuntimeError('*** Session key unavailable ***')
return self.session_key, self.refresh_token
def list_test(self):
if self.session_key is None:
raise RuntimeError('*** Session key unavailable ***')
cfg = {
'service': 'credentials/list',
'tests': [
{ # 1
'name': 'maxResults 1',
'headers': { 'Authorization': 'Bearer ' + self.session_key },
'input': { 'maxResults': 1 },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'credentialIDs' ] },
{ 'condition': 'not in', 'arg': [ 'error' ] },
{ 'condition': '<', 'arg': { 'credentialIDs': 2 } }
]
},
{ # 2
'name': 'maxResults 5',
'headers': { 'Authorization': 'Bearer ' + self.session_key },
'input': { 'maxResults': 5 },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'credentialIDs' ] },
{ 'condition': 'not in', 'arg': [ 'error' ] },
{ 'condition': '<', 'arg': { 'credentialIDs': 6 } }
]
},
{ # 3
'name': 'maxResults 20',
'headers': { 'Authorization': 'Bearer ' + self.session_key },
'input': { 'maxResults': 20 },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'credentialIDs' ] },
{ 'condition': 'not in', 'arg': [ 'error' ] },
{ 'condition': '<', 'arg': { 'credentialIDs': 21 } }
]
}
]
}
self._generic_test(cfg)
self.credential_IDs = self.list_utility(64)
if len(self.credential_IDs) > 1:
chunk_size = len(self.credential_IDs) // 5 + 1
if len(self.list_utility(chunk_size, 5)) == len(self.credential_IDs):
self.logger.info(f'[ {CSC.highlight("OK", "green", bold=True)} ] credentials/list - pagination test')
else:
self.logger.error(f'[ {CSC.highlight("KO", "red", bold=True)} ] credentials/list - pagination test')
return self.credential_IDs
def list_utility(self, max_results=1, iterations=-1):
if self.session_key is None:
raise RuntimeError('*** Session key unavailable ***')
credentials_ids = []
payload = { 'maxResults': max_results }
dots_num = 0
while iterations != 0:
r = requests.post(self.service_URLs['credentials/list'], verify=False, headers={ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + self.session_key }, json=payload)
if r.text is not None and str(r.text) != '':
try:
j = r.json()
except ValueError:
self.logger.error(CSC.highlight('Invalid json response while iterating credentials list', 'red', bold=True))
break
else:
self.logger.error(CSC.highlight('Invalid response while iterating credentials list', 'red', bold=True))
break
if 'error' in j:
break
elif 'credentialIDs' in j and isinstance(j['credentialIDs'], list):
credentials_ids.extend(j['credentialIDs'])
if 'nextPageToken' not in j:
break
payload['pageToken'] = j['nextPageToken']
iterations = iterations if iterations < 0 else iterations - 1
sys.stdout.write("\r\033[K" if dots_num is 5 else ". ")
dots_num = (dots_num + 1) % 6
sys.stdout.flush()
sys.stdout.write("\r\033[K")
sys.stdout.flush()
return credentials_ids
def credentials_info_test(self, credential_id=None, auth_mode='explicit'):
if self.session_key is None:
raise RuntimeError('*** Session key unavailable ***')
cfg = {
'service': 'credentials/info',
'tests': [
{ # 1
'name': 'credential_id only',
'headers': { 'Authorization': 'Bearer ' + self.session_key },
'input': { 'credentialID': credential_id },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'cert>certificates', 'key>status', 'key>algo', 'key>len' ] },
{ 'condition': 'not in', 'arg': [ 'error', 'error_description', 'PIN', 'OTP', 'cert>validFrom', 'cert>validTo', 'cert>subjectDN', 'cert>serialNumber', 'cert>issuerDN' ] },
{ 'condition': '=', 'arg': { 'cert>certificates': 1 } },
{ 'condition': 'eq', 'arg': { 'key>algo': [ "1.2.840.113549.1.1.1", "1.2.840.113549.1.1.5", "1.2.840.113549.1.1.14", "1.2.840.113549.1.1.11", "1.2.840.113549.1.1.12", "1.2.840.113549.1.1.13", "1.2.840.113549.1.1.10" ] } }
]
},
{ # 2
'name': 'certificates none',
'headers': { 'Authorization': 'Bearer ' + self.session_key },
'input': { 'credentialID': credential_id, 'certificates': 'none' },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'cert', 'key>status', 'key>algo', 'key>len' ] },
{ 'condition': 'not in', 'arg': [ 'error', 'error_description', 'cert>validFrom', 'cert>validTo', 'cert>certificates', 'cert>subjectDN', 'cert>serialNumber', 'cert>issuerDN', 'PIN', 'OTP' ] },
{ 'condition': 'eq', 'arg': { 'key>algo': [ "1.2.840.113549.1.1.1", "1.2.840.113549.1.1.5", "1.2.840.113549.1.1.14", "1.2.840.113549.1.1.11", "1.2.840.113549.1.1.12", "1.2.840.113549.1.1.13", "1.2.840.113549.1.1.10" ] } }
]
},
{ # 3
'name': 'certificates single',
'headers': { 'Authorization': 'Bearer ' + self.session_key },
'input': { 'credentialID': credential_id, 'certificates': 'single' },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'cert>certificates', 'key>status', 'key>algo', 'key>len' ] },
{ 'condition': 'not in', 'arg': [ 'error', 'error_description', 'cert>validFrom', 'cert>validTo', 'cert>subjectDN', 'cert>serialNumber', 'cert>issuerDN', 'PIN', 'OTP' ] },
{ 'condition': '=', 'arg': { 'cert>certificates': 1 } },
{ 'condition': 'eq', 'arg': { 'key>algo': [ "1.2.840.113549.1.1.1", "1.2.840.113549.1.1.5", "1.2.840.113549.1.1.14", "1.2.840.113549.1.1.11", "1.2.840.113549.1.1.12", "1.2.840.113549.1.1.13", "1.2.840.113549.1.1.10" ] } }
]
},
{ # 4
'name': 'certificates chain',
'headers': { 'Authorization': 'Bearer ' + self.session_key },
'input': { 'credentialID': credential_id, 'certificates': 'chain' },
'exp_result': [
{ 'condition': 'in', 'arg': [ 'cert>certificates', 'key>status', 'key>algo', 'key>len' ] },