-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathregister.py
2387 lines (2136 loc) · 121 KB
/
register.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
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Commander
# Copyright 2022 Keeper Security Inc.
# Contact: [email protected]
#
import argparse
import datetime
import getpass
import hashlib
import itertools
import json
import logging
import math
import re
import time
import urllib.parse
from typing import Optional, Dict, Iterable, Any, Set, List
from urllib.parse import urlunparse
from tabulate import tabulate
from . import base
from .base import dump_report_data, field_to_title, fields_to_titles, raise_parse_exception, suppress_exit, Command, \
GroupCommand, FolderMixin
from .helpers.record import get_record_uids
from .helpers.timeout import parse_timeout
from .record import RecordRemoveCommand
from .utils import SyncDownCommand
from .. import api, utils, crypto, constants, rest_api
from ..display import bcolors
from ..error import KeeperApiError, CommandError, Error
from ..params import KeeperParams
from ..proto import APIRequest_pb2, folder_pb2, record_pb2, enterprise_pb2
from ..shared_record import SharePermissions, get_shared_records, SharedRecord
from ..sox.sox_types import Record
from ..subfolder import BaseFolderNode, SharedFolderNode, SharedFolderFolderNode, try_resolve_path, get_folder_path, \
get_folder_uids, get_contained_record_uids
from ..loginv3 import LoginV3API
def register_commands(commands):
commands['share-record'] = ShareRecordCommand()
commands['share-folder'] = ShareFolderCommand()
commands['share-report'] = ShareReportCommand()
commands['record-permission'] = RecordPermissionCommand()
commands['find-duplicate'] = FindDuplicateCommand()
commands['one-time-share'] = OneTimeShareCommand()
commands['create-account'] = CreateRegularUserCommand()
commands['find-ownerless'] = FindOwnerlessCommand()
# commands['file-report'] = FileReportCommand()
def register_command_info(aliases, command_info):
aliases['sr'] = 'share-record'
aliases['sf'] = 'share-folder'
aliases['ots'] = 'one-time-share'
aliases['share'] = 'one-time-share'
for p in [share_record_parser, share_folder_parser, share_report_parser, record_permission_parser,
find_duplicate_parser]:
command_info[p.prog] = p.description
command_info['share'] = 'Manage One-Time Shares'
share_record_parser = argparse.ArgumentParser(prog='share-record', description='Change the sharing permissions of an individual record')
share_record_parser.add_argument('-e', '--email', dest='email', action='append', required=True, help='account email')
share_record_parser.add_argument('-a', '--action', dest='action', choices=['grant', 'revoke', 'owner', 'cancel'],
default='grant', action='store', help='user share action. \'grant\' if omitted')
share_record_parser.add_argument('-s', '--share', dest='can_share', action='store_true', help='can re-share record')
share_record_parser.add_argument('-w', '--write', dest='can_edit', action='store_true', help='can modify record')
share_record_parser.add_argument('-R', '--recursive', dest='recursive', action='store_true', help='apply command to shared folder hierarchy')
share_record_parser.add_argument('--dry-run', dest='dry_run', action='store_true', help='display the permissions changes without committing them')
expiration = share_record_parser.add_mutually_exclusive_group()
expiration.add_argument('--expire-at', dest='expire_at', action='store',
help='share expiration: never or UTC datetime')
expiration.add_argument('--expire-in', dest='expire_in', action='store',
metavar='<NUMBER>[(mi)nutes|(h)ours|(d)ays|(mo)nths|(y)ears]',
help='share expiration: never or period')
share_record_parser.add_argument('record', nargs='?', type=str, action='store', help='record/shared folder path/UID')
share_folder_parser = argparse.ArgumentParser(prog='share-folder', description='Change a shared folders permissions.')
share_folder_parser.add_argument('-a', '--action', dest='action', choices=['grant', 'revoke', 'remove'], default='grant',
action='store', help='shared folder action. \'grant\' if omitted')
share_folder_parser.add_argument('-e', '--email', dest='user', action='append',
help='account email, team, @existing for all users and teams in the folder, '
'or \'*\' as default folder permission')
share_folder_parser.add_argument('-r', '--record', dest='record', action='append',
help='record name, record UID, @existing for all records in the folder,'
' or \'*\' as default folder permission')
share_folder_parser.add_argument('-p', '--manage-records', dest='manage_records', action='store_true',
help='account permission: can manage records.')
share_folder_parser.add_argument('-o', '--manage-users', dest='manage_users', action='store_true',
help='account permission: can manage users.')
share_folder_parser.add_argument('-s', '--can-share', dest='can_share', action='store_true',
help='record permission: can be shared')
share_folder_parser.add_argument('-d', '--can-edit', dest='can_edit', action='store_true',
help='record permission: can be modified.')
share_folder_parser.add_argument('-f', '--force', dest='force', action='store_true',
help='Apply permission changes ignoring default folder permissions. Used on the '
'initial sharing action')
expiration = share_folder_parser.add_mutually_exclusive_group()
expiration.add_argument('--expire-at', dest='expire_at', action='store', metavar='TIMESTAMP',
help='share expiration: never or ISO datetime (yyyy-MM-dd[ hh:mm:ss])')
expiration.add_argument('--expire-in', dest='expire_in', action='store', metavar='PERIOD',
help='share expiration: never or period (<NUMBER>[(y)ears|(mo)nths|(d)ays|(h)ours(mi)nutes]')
share_folder_parser.add_argument('folder', nargs='+', type=str, action='store', help='shared folder path or UID')
share_report_parser = argparse.ArgumentParser(prog='share-report', description='Display report of shared records.')
share_report_parser.add_argument('--format', dest='format', action='store', choices=['table', 'json', 'csv'],
default='table', help='output format.')
share_report_parser.add_argument('--output', dest='output', action='store',
help='output file name. (ignored for table format)')
share_report_parser.add_argument('-r', '--record', dest='record', action='append', help='record name or UID')
share_report_parser.add_argument('-e', '--email', dest='user', action='append', help='user email or team name')
share_report_parser.add_argument('-o', '--owner', dest='owner', action='store_true',
help='record ownership information')
share_report_parser.add_argument('--share-date', dest='share_date', action='store_true',
help='include date when the record was shared. This flag will only apply to the '
'detailed owner report. This data is available only to those users who have '
'permissions to execute reports for their company. Example of the report that '
'includes shared date: `share-report -v -o --share-date --format table`')
share_report_parser.add_argument('-sf', '--shared-folders', dest='shared_folders', action='store_true',
help='display shared folder detail information. If omitted then records.')
share_report_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='display verbose information')
share_report_parser.add_argument('-f', '--folders', dest='folders', action='store_true', default=False,
help='limit report to shared folders (excludes shared records)')
tu_help = 'show shared-folder team members (to be used with "--folders"/ "-f" flag, ignored for non-admin accounts)'
share_report_parser.add_argument('-tu', '--show-team-users', action='store_true', help=tu_help)
container_filter_help = 'path(s) or UID(s) of container(s) by which to filter records'
share_report_parser.add_argument('container', nargs='*', type=str, action='store', help=container_filter_help)
record_permission_parser = argparse.ArgumentParser(prog='record-permission', description='Modify a records permissions.')
record_permission_parser.add_argument('--dry-run', dest='dry_run', action='store_true',
help='Display the permissions changes without committing them')
record_permission_parser.add_argument('--force', dest='force', action='store_true',
help='Apply permission changes without any confirmation')
record_permission_parser.add_argument('-R', '--recursive', dest='recursive', action='store_true',
help='Apply permission changes to all sub-folders')
record_permission_parser.add_argument('--share-record', dest='share_record', action='store_true',
help='Change a records sharing permissions')
record_permission_parser.add_argument('--share-folder', dest='share_folder', action='store_true',
help='Change a folders sharing permissions')
record_permission_parser.add_argument('-a', '--action', dest='action', action='store', choices=['grant', 'revoke'],
required=True, help='The action being taken')
record_permission_parser.add_argument('-s', '--can-share', dest='can_share', action='store_true',
help='Set record permission: can be shared')
record_permission_parser.add_argument('-d', '--can-edit', dest='can_edit', action='store_true',
help='Set record permission: can be edited')
record_permission_parser.add_argument('folder', nargs='?', type=str, action='store', help='folder path or folder UID')
record_permission_parser.error = raise_parse_exception
record_permission_parser.exit = suppress_exit
find_ownerless_desc = 'List (and, optionally, claim) records in the user\'s vault that currently do not have an owner'
find_ownerless_parser = argparse.ArgumentParser(prog='find-ownerless', description=find_ownerless_desc)
find_ownerless_parser.add_argument('--format', dest='format', action='store', choices=['csv', 'json', 'table'],
default='table', help='output format')
find_ownerless_parser.add_argument('--output', dest='output', action='store',
help='output file name (ignored for table format)')
find_ownerless_parser.add_argument('--claim', dest='claim', action='store_true', help='claim records found')
find_ownerless_parser.add_argument('-v', '--verbose', action='store_true', help='output details for each record found')
folder_help = 'path or UID of folder to search (optional, with multiple values allowed)'
find_ownerless_parser.add_argument('folder', nargs='*', type=str, action='store', help=folder_help)
find_ownerless_parser.error = raise_parse_exception
find_ownerless_parser.exit = suppress_exit
find_duplicate_parser = argparse.ArgumentParser(prog='find-duplicate', description='List duplicated records.')
find_duplicate_parser.add_argument('--title', dest='title', action='store_true', help='Match duplicates by title.')
find_duplicate_parser.add_argument('--login', dest='login', action='store_true', help='Match duplicates by login.')
find_duplicate_parser.add_argument('--password', dest='password', action='store_true', help='Match duplicates by password.')
find_duplicate_parser.add_argument('--url', dest='url', action='store_true', help='Match duplicates by URL.')
find_duplicate_parser.add_argument('--shares', action='store_true', help='Match duplicates by share permissions')
find_duplicate_parser.add_argument('--full', dest='full', action='store_true', help='Match duplicates by all fields.')
merge_help = 'Consolidate duplicate records (matched by all fields, including shares)'
find_duplicate_parser.add_argument('-m', '--merge', action='store_true', help=merge_help)
ignore_shares_txt = 'ignore share permissions when grouping duplicate records to merge'
find_duplicate_parser.add_argument('--ignore-shares-on-merge', action='store_true', help=ignore_shares_txt)
force_help = 'Delete duplicates w/o being prompted for confirmation (valid only w/ --merge option)'
find_duplicate_parser.add_argument('-f', '--force', action='store_true', help=force_help)
dry_run_help = 'Simulate removing duplicates (with this flog, no records are ever removed or modified). ' \
'Valid only w/ --merge flag'
find_duplicate_parser.add_argument('-n', '--dry-run', action='store_true', help=dry_run_help)
find_duplicate_parser.add_argument('-q', '--quiet', action='store_true',
help='Suppress screen output, valid only w/ --force flag')
scope_help = 'The scope of the search (limited to current vault if not specified)'
find_duplicate_parser.add_argument('-s', '--scope', action='store', choices=['vault', 'enterprise'], default='vault',
help=scope_help)
refresh_help = 'Populate local cache with latest compliance data . Valid only w/ --scope=enterprise option.'
find_duplicate_parser.add_argument('-r', '--refresh-data', action='store_true', help=refresh_help)
find_duplicate_parser.add_argument('--format', action='store', choices=['table', 'csv', 'json'], default='table',
help='output format.')
find_duplicate_parser.add_argument('--output', action='store', help='output file name. (ignored for table format)')
find_duplicate_parser.error = raise_parse_exception
find_duplicate_parser.exit = suppress_exit
one_time_share_create_parser = argparse.ArgumentParser(prog='one-time-share-create', description='Creates one-time share URL for a record')
one_time_share_create_parser.add_argument('--output', dest='output', choices=['clipboard', 'stdout'],
action='store', help='password output destination')
one_time_share_create_parser.add_argument('--name', dest='share_name', action='store', help='one-time share URL name')
one_time_share_create_parser.add_argument('-e', '--expire', dest='expire', action='store', metavar='<NUMBER>[(m)inutes|(h)ours|(d)ays]',
help='Time period record share URL is valid.')
one_time_share_create_parser.add_argument('record', nargs='?', type=str, action='store', help='record path or UID')
one_time_share_list_parser = argparse.ArgumentParser(prog='one-time-share-list', description='Displays a list of one-time shares for a records')
one_time_share_list_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='verbose output.')
one_time_share_list_parser.add_argument('-a', '--all', dest='show_all', action='store_true', help='show all one-time shares including expired.')
one_time_share_list_parser.add_argument('--format', dest='format', action='store', choices=['table', 'csv', 'json'],
default='table', help='output format.')
one_time_share_list_parser.add_argument('--output', dest='output', action='store',
help='output file name. (ignored for table format)')
one_time_share_list_parser.add_argument('record', nargs='?', type=str, action='store', help='record path or UID')
one_time_share_remove_parser = argparse.ArgumentParser(prog='one-time-share-remove', description='Removes one-time share URL for a record')
one_time_share_remove_parser.add_argument('record', nargs='?', type=str, action='store', help='record path or UID')
one_time_share_remove_parser.add_argument('share', nargs='?', type=str, action='store', help='one-time share name or ID')
create_account_parser = argparse.ArgumentParser(prog='create-account', description='Create Keeper Account')
create_account_parser.add_argument('email', help='email')
def get_share_expiration(expire_at, expire_in): # (Optional[str], Optional[str]) -> Optional[int]
if not expire_at and not expire_in:
return
dt = None # type: Optional[datetime.datetime]
if isinstance(expire_at, str):
if expire_at == 'never':
return -1
dt = datetime.datetime.fromisoformat(expire_at)
elif isinstance(expire_in, str):
if expire_in == 'never':
return -1
td = parse_timeout(expire_in)
dt = datetime.datetime.now() + td
if dt is None:
raise ValueError(f'Incorrect expiration: {expire_at or expire_in}')
return int(dt.timestamp())
class ShareFolderCommand(Command):
def get_parser(self):
return share_folder_parser
def execute(self, params, **kwargs):
def get_share_admin_obj_uids(obj_names, obj_type):
# type: (List[Optional[str], int], int) -> Optional[Set[str]]
if not obj_names:
return None
try:
rq = record_pb2.AmIShareAdmin()
for name in obj_names:
try:
uid = utils.base64_url_decode(name)
if isinstance(uid, bytes) and len(uid) == 16:
osa = record_pb2.IsObjectShareAdmin()
osa.uid = uid
osa.objectType = obj_type
rq.isObjectShareAdmin.append(osa)
except:
pass
if len(rq.isObjectShareAdmin) > 0:
rs = api.communicate_rest(params, rq, 'vault/am_i_share_admin', rs_type=record_pb2.AmIShareAdmin)
sa_obj_uids = {sa_obj.uid for sa_obj in rs.isObjectShareAdmin if sa_obj.isAdmin}
sa_obj_uids = {utils.base64_url_encode(uid) for uid in sa_obj_uids}
return sa_obj_uids
except Error as e:
print(f'get_share_admin: msg = {e.message}')
return None
names = kwargs.get('folder')
if not isinstance(names, list):
names = [names]
all_folders = any(True for x in names if x == '*')
if all_folders:
names = [x for x in names if x != '*']
shared_folder_uids = set() # type: Set[str]
if all_folders:
shared_folder_uids.update(params.shared_folder_cache.keys())
else:
get_folder_by_uid = lambda uid: params.folder_cache.get(uid)
folder_uids = {uid for name in names for uid in get_folder_uids(params, name)}
folders = {get_folder_by_uid(uid) for uid in folder_uids}
shared_folder_uids.update([uid for uid in folder_uids if uid in params.shared_folder_cache])
sf_subfolders = {f for f in folders if f.type == 'shared_folder_folder'}
shared_folder_uids.update({subfolder.shared_folder_uid for subfolder in sf_subfolders})
unresolved_names = [name for name in names if not get_folder_uids(params, name)]
share_admin_folder_uids = get_share_admin_obj_uids(unresolved_names, record_pb2.CHECK_SA_ON_SF)
shared_folder_uids.update(share_admin_folder_uids or [])
if not shared_folder_uids:
raise CommandError('share-folder', 'Enter name of at least one existing folder')
action = kwargs.get('action') or 'grant'
share_expiration = None
if action == 'grant':
share_expiration = get_share_expiration(kwargs.get('expire_at'), kwargs.get('expire_in'))
as_users = set()
as_teams = set()
all_users = False
default_account = False
if 'user' in kwargs:
for u in (kwargs.get('user') or []):
if u == '*':
default_account = True
elif u in ('@existing', '@current'):
all_users = True
else:
em = re.match(constants.EMAIL_PATTERN, u)
if em is not None:
as_users.add(u.lower())
else:
api.load_available_teams(params)
team = next((x for x in params.available_team_cache
if u == x.get('team_uid') or
u.lower() == (x.get('team_name') or '').lower()), None)
if team:
team_uid = team['team_uid']
as_teams.add(team_uid)
else:
logging.warning('User %s could not be resolved as email or team', u)
record_uids = set()
all_records = False
default_record = False
unresolved_names = []
if 'record' in kwargs:
records = kwargs.get('record') or []
for r in records:
if r == '*':
default_record = True
elif r in ('@existing', '@current'):
all_records = True
else:
r_uids = get_record_uids(params, r)
record_uids.update(r_uids) if r_uids else unresolved_names.append(r)
if unresolved_names:
sa_record_uids = get_share_admin_obj_uids(unresolved_names, record_pb2.CHECK_SA_ON_RECORD)
record_uids.update(sa_record_uids or {})
if len(as_users) == 0 and len(as_teams) == 0 and len(record_uids) == 0 and \
not default_record and not default_account and \
not all_users and not all_records:
logging.info('Nothing to do')
return
rq_groups = []
def prep_rq(recs, users, curr_sf):
return self.prepare_request(params, kwargs, curr_sf, users, sf_teams, recs, default_record=default_record,
default_account=default_account, share_expiration=share_expiration)
for sf_uid in shared_folder_uids:
sf_users = as_users.copy()
sf_teams = as_teams.copy()
sf_records = record_uids.copy()
if sf_uid in params.shared_folder_cache:
sh_fol = params.shared_folder_cache[sf_uid]
if all_users or all_records:
if all_users:
if 'users' in sh_fol:
sf_users.update((x['username'] for x in sh_fol['users'] if x['username'] != params.user))
if 'teams' in sh_fol:
sf_teams.update((x['team_uid'] for x in sh_fol['teams']))
if all_records:
if 'records' in sh_fol:
sf_records.update((x['record_uid'] for x in sh_fol['records']))
else:
sh_fol = {
'shared_folder_uid': sf_uid,
'users': [{'username': x, 'manage_records': action != 'grant', 'manage_users': action != 'grant'}
for x in as_users],
'teams': [{'team_uid': x, 'manage_records': action != 'grant', 'manage_users': action != 'grant'}
for x in as_teams],
'records': [{'record_uid': x, 'can_share': action != 'grant', 'can_edit': action != 'grant'}
for x in record_uids]
}
chunk_size = 500
rec_list = list(sf_records)
user_list = list(sf_users)
num_rec_chunks = math.ceil(len(sf_records) / chunk_size)
num_user_chunks = math.ceil(len(sf_users) / chunk_size)
num_rq_groups = num_user_chunks or 1 * num_rec_chunks or 1
while len(rq_groups) < num_rq_groups:
rq_groups.append([])
rec_chunks = [rec_list[i * chunk_size:(i + 1) * chunk_size] for i in range(num_rec_chunks)] or [[]]
user_chunks = [user_list[i * chunk_size:(i + 1) * chunk_size] for i in range(num_user_chunks)] or [[]]
group_idx = 0
for r_chunk in rec_chunks:
for u_chunk in user_chunks:
sf_info = sh_fol.copy()
if group_idx:
del sf_info['revision']
rq_groups[group_idx].append(prep_rq(r_chunk, u_chunk, sf_info))
group_idx += 1
self.send_requests(params, rq_groups)
@staticmethod
def prepare_request(params, kwargs, curr_sf, users, teams, rec_uids, *,
default_record=False, default_account=False,
share_expiration=None):
rq = folder_pb2.SharedFolderUpdateV3Request()
rq.sharedFolderUid = utils.base64_url_decode(curr_sf['shared_folder_uid'])
if 'revision' in curr_sf:
rq.revision = curr_sf['revision']
else:
rq.forceUpdate = True
action = kwargs.get('action') or 'grant'
mr = kwargs.get('manage_records')
mu = kwargs.get('manage_users')
if default_account and action != 'remove':
if mr:
rq.defaultManageRecords = folder_pb2.BOOLEAN_TRUE if action == 'grant' else folder_pb2.BOOLEAN_FALSE
else:
rq.defaultManageRecords = folder_pb2.BOOLEAN_NO_CHANGE
if mu:
rq.defaultManageUsers = folder_pb2.BOOLEAN_TRUE if action == 'grant' else folder_pb2.BOOLEAN_FALSE
else:
rq.defaultManageUsers = folder_pb2.BOOLEAN_NO_CHANGE
if len(users) > 0:
existing_users = {x['username'] for x in curr_sf.get('users', [])}
for email in users:
uo = folder_pb2.SharedFolderUpdateUser()
uo.username = email
if isinstance(share_expiration, int):
if share_expiration > 0:
uo.expiration = share_expiration * 1000
uo.timerNotificationType = record_pb2.NOTIFY_OWNER
elif share_expiration < 0:
uo.expiration = -1
if email in existing_users:
if action == 'grant':
uo.manageRecords = folder_pb2.BOOLEAN_TRUE if mr else folder_pb2.BOOLEAN_NO_CHANGE
uo.manageUsers = folder_pb2.BOOLEAN_TRUE if mu else folder_pb2.BOOLEAN_NO_CHANGE
rq.sharedFolderUpdateUser.append(uo)
elif action == 'revoke':
uo.manageRecords = folder_pb2.BOOLEAN_FALSE if mr else folder_pb2.BOOLEAN_NO_CHANGE
uo.manageUsers = folder_pb2.BOOLEAN_FALSE if mu else folder_pb2.BOOLEAN_NO_CHANGE
rq.sharedFolderUpdateUser.append(uo)
elif action == 'remove':
rq.sharedFolderRemoveUser.append(uo.username)
elif action == 'grant':
invited = api.load_user_public_keys(params, [email], send_invites=True)
if invited:
for username in invited:
logging.warning('Share invitation has been sent to \'%s\'', username)
logging.warning('Please repeat this command when invitation is accepted.')
keys = params.key_cache.get(email)
if keys and keys.rsa:
uo.manageRecords = folder_pb2.BOOLEAN_TRUE if mr or curr_sf.get('default_manage_records') is True else folder_pb2.BOOLEAN_FALSE
uo.manageUsers = folder_pb2.BOOLEAN_TRUE if mu or curr_sf.get('default_manage_users') is True else folder_pb2.BOOLEAN_FALSE
sf_key = curr_sf.get('shared_folder_key_unencrypted') # type: Optional[bytes]
if sf_key:
rsa_key = crypto.load_rsa_public_key(keys.rsa)
uo.sharedFolderKey = crypto.encrypt_rsa(sf_key, rsa_key)
rq.sharedFolderAddUser.append(uo)
else:
logging.warning('User %s not found', email)
if len(teams) > 0:
existing_teams = {x['team_uid']: x for x in curr_sf.get('teams', [])}
for team_uid in teams:
to = folder_pb2.SharedFolderUpdateTeam()
to.teamUid = utils.base64_url_decode(team_uid)
if isinstance(share_expiration, int):
if share_expiration > 0:
to.expiration = share_expiration * 1000
to.timerNotificationType = record_pb2.NOTIFY_OWNER
elif share_expiration < 0:
to.expiration = -1
if team_uid in existing_teams:
team = existing_teams[team_uid]
if action == 'grant':
to.manageRecords = True if mr else team.get('manage_records', False)
to.manageUsers = True if mu else team.get('manage_users', False)
rq.sharedFolderUpdateTeam.append(to)
elif action == 'revoke':
to.manageRecords = False if mr else team.get('manage_records', False)
to.manageUsers = False if mu else team.get('manage_users', False)
rq.sharedFolderUpdateTeam.append(to)
elif action == 'remove':
rq.sharedFolderRemoveTeam.append(to.teamUid)
elif action == 'grant':
to.manageRecords = True if mr else curr_sf.get('default_manage_records') is True
to.manageUsers = True if mu else curr_sf.get('default_manage_users') is True
sf_key = curr_sf.get('shared_folder_key_unencrypted') # type: Optional[bytes]
if sf_key:
if team_uid in params.team_cache:
team = params.team_cache[team_uid]
to.sharedFolderKey = crypto.encrypt_aes_v1(sf_key, team['team_key_unencrypted'])
else:
api.load_team_keys(params, [team_uid])
keys = params.key_cache.get(team_uid)
if keys:
if keys.aes:
to.sharedFolderKey = crypto.encrypt_aes_v1(sf_key, keys.aes)
elif keys.rsa:
rsa_key = crypto.load_rsa_public_key(keys.rsa)
to.sharedFolderKey = crypto.encrypt_rsa(sf_key, rsa_key)
else:
continue
else:
continue
else:
logging.info('Shared folder key is not available.')
rq.sharedFolderAddTeam.append(to)
ce = kwargs.get('can_edit')
cs = kwargs.get('can_share')
if default_record:
if ce and action != 'remove':
rq.defaultCanEdit = folder_pb2.BOOLEAN_TRUE if action == 'grant' else folder_pb2.BOOLEAN_FALSE
else:
rq.defaultCanEdit = folder_pb2.BOOLEAN_NO_CHANGE
if cs and action != 'remove':
rq.defaultCanShare = folder_pb2.BOOLEAN_TRUE if action == 'grant' else folder_pb2.BOOLEAN_FALSE
else:
rq.defaultCanShare = folder_pb2.BOOLEAN_NO_CHANGE
if len(rec_uids) > 0:
existing_records = {x['record_uid'] for x in curr_sf.get('records', [])}
for record_uid in rec_uids:
ro = folder_pb2.SharedFolderUpdateRecord()
ro.recordUid = utils.base64_url_decode(record_uid)
if isinstance(share_expiration, int):
if share_expiration > 0:
ro.expiration = share_expiration * 1000
ro.timerNotificationType = record_pb2.NOTIFY_OWNER
elif share_expiration < 0:
ro.expiration = -1
if record_uid in existing_records:
if action == 'grant':
ro.canEdit = folder_pb2.BOOLEAN_TRUE if ce else folder_pb2.BOOLEAN_NO_CHANGE
ro.canShare = folder_pb2.BOOLEAN_TRUE if cs else folder_pb2.BOOLEAN_NO_CHANGE
rq.sharedFolderUpdateRecord.append(ro)
elif action == 'revoke':
ro.canEdit = folder_pb2.BOOLEAN_FALSE if ce else folder_pb2.BOOLEAN_NO_CHANGE
ro.canShare = folder_pb2.BOOLEAN_FALSE if cs else folder_pb2.BOOLEAN_NO_CHANGE
rq.sharedFolderUpdateRecord.append(ro)
elif action == 'remove':
rq.sharedFolderRemoveRecord.append(ro.recordUid)
else:
if action == 'grant':
ro.canEdit = folder_pb2.BOOLEAN_TRUE if ce or curr_sf.get('default_can_edit') is True else folder_pb2.BOOLEAN_FALSE
ro.canShare = folder_pb2.BOOLEAN_TRUE if cs or curr_sf.get('default_can_share') is True else folder_pb2.BOOLEAN_FALSE
sf_key = curr_sf.get('shared_folder_key_unencrypted')
if sf_key:
rec = params.record_cache[record_uid]
rec_key = rec['record_key_unencrypted']
if rec.get('version', 0) < 3:
ro.encryptedRecordKey = crypto.encrypt_aes_v1(rec_key, sf_key)
else:
ro.encryptedRecordKey = crypto.encrypt_aes_v2(rec_key, sf_key)
rq.sharedFolderAddRecord.append(ro)
return rq
@staticmethod
def send_requests(params, partitioned_requests):
for requests in partitioned_requests:
while requests:
params.sync_data = True
chunk = requests[:999]
requests = requests[999:]
rqs = folder_pb2.SharedFolderUpdateV3RequestV2()
rqs.sharedFoldersUpdateV3.extend(chunk)
try:
rss = api.communicate_rest(params, rqs, 'vault/shared_folder_update_v3', payload_version=1,
rs_type=folder_pb2.SharedFolderUpdateV3ResponseV2)
for rs in rss.sharedFoldersUpdateV3Response:
team_cache = params.available_team_cache or []
for attr in (
'sharedFolderAddTeamStatus', 'sharedFolderUpdateTeamStatus',
'sharedFolderRemoveTeamStatus'):
if hasattr(rs, attr):
statuses = getattr(rs, attr)
for t in statuses:
team_uid = utils.base64_url_encode(t.teamUid)
team = next((x for x in team_cache if x.get('team_uid') == team_uid), None)
if team:
status = t.status
if status == 'success':
logging.info('Team share \'%s\' %s', team['team_name'],
'added' if attr == 'sharedFolderAddTeamStatus' else
'updated' if attr == 'sharedFolderUpdateTeamStatus' else
'removed')
else:
logging.warning('Team share \'%s\' failed', team['team_name'])
for attr in (
'sharedFolderAddUserStatus', 'sharedFolderUpdateUserStatus',
'sharedFolderRemoveUserStatus'):
if hasattr(rs, attr):
statuses = getattr(rs, attr)
for s in statuses:
username = s.username
status = s.status
if status == 'success':
logging.info('User share \'%s\' %s', username,
'added' if attr == 'sharedFolderAddUserStatus' else
'updated' if attr == 'sharedFolderUpdateUserStatus' else
'removed')
elif status == 'invited':
logging.info('User \'%s\' invited', username)
else:
logging.warning('User share \'%s\' failed', username)
for attr in ('sharedFolderAddRecordStatus', 'sharedFolderUpdateRecordStatus',
'sharedFolderRemoveRecordStatus'):
if hasattr(rs, attr):
statuses = getattr(rs, attr)
for r in statuses:
record_uid = utils.base64_url_encode(r.recordUid)
status = r.status
if record_uid in params.record_cache:
rec = api.get_record(params, record_uid)
title = rec.title
else:
title = record_uid
if status == 'success':
logging.info('Record share \'%s\' %s', title,
'added' if attr == 'sharedFolderAddRecordStatus' else
'updated' if attr == 'sharedFolderUpdateRecordStatus' else
'removed')
else:
logging.warning('Record share \'%s\' failed', title)
except KeeperApiError as kae:
if kae.result_code != 'bad_inputs_nothing_to_do':
raise kae
class ShareRecordCommand(Command):
def get_parser(self):
return share_record_parser
def execute(self, params, **kwargs):
emails = kwargs.get('email') or []
if not emails:
raise CommandError('share-record', '\'email\' parameter is missing')
action = kwargs.get('action') or 'grant'
if action == 'cancel':
answer = base.user_choice(
bcolors.FAIL + bcolors.BOLD + '\nALERT!\n' + bcolors.ENDC + 'This action cannot be undone.\n\n' +
'Do you want to cancel all shares with user(s): ' + ', '.join(emails) + ' ?', 'yn', 'n')
if answer.lower() in {'y', 'yes'}:
for email in emails:
rq = {
'command': 'cancel_share',
'to_email': email
}
try:
api.communicate(params, rq)
except KeeperApiError as kae:
if kae.result_code == 'share_not_found':
logging.info('{0}: No shared records are found.'.format(email))
else:
logging.warning('{0}: {1}.'.format(email, kae.message))
except Exception as e:
logging.warning('{0}: {1}.'.format(email, e))
params.sync_data = True
return
name = kwargs.get('record')
if not name:
self.get_parser().print_help()
return
share_expiration = None
if action == 'grant':
share_expiration = get_share_expiration(kwargs.get('expire_at'), kwargs.get('expire_in'))
record_uid = None
folder_uid = None
shared_folder_uid = None
if name in params.record_cache:
record_uid = name
elif name in params.folder_cache:
folder = params.folder_cache[name] # type: BaseFolderNode
if isinstance(folder, (SharedFolderNode, SharedFolderFolderNode)):
folder_uid = folder.uid
if isinstance(folder, SharedFolderFolderNode):
shared_folder_uid = folder.shared_folder_uid
else:
shared_folder_uid = folder.uid
elif name in params.shared_folder_cache:
shared_folder_uid = name
else:
for shared_folder in params.shared_folder_cache.values():
shared_folder_name = shared_folder.get('name_unencrypted', '').lower()
if name == shared_folder_name:
shared_folder_uid = shared_folder['shared_folder_uid']
break
if 'records' in shared_folder:
if any((True for x in shared_folder['records'] if x['record_uid'] == name)):
record_uid = name
shared_folder_uid = shared_folder['shared_folder_uid']
break
if shared_folder_uid is None and record_uid is None:
rs = try_resolve_path(params, name)
if rs is not None:
folder, name = rs
if name:
for uid in params.subfolder_record_cache.get(folder.uid or ''):
r = api.get_record(params, uid)
if r.title.lower() == name.lower():
record_uid = uid
break
else:
if isinstance(folder, (SharedFolderNode, SharedFolderFolderNode)):
folder_uid = folder.uid
shared_folder_uid = folder_uid if isinstance(folder, SharedFolderNode) \
else folder.shared_folder_uid
is_share_admin = False
if record_uid is None and folder_uid is None and shared_folder_uid is None:
if params.enterprise:
try:
uid = utils.base64_url_decode(name)
if isinstance(uid, bytes) and len(uid) == 16:
rq = record_pb2.AmIShareAdmin()
osa = record_pb2.IsObjectShareAdmin()
osa.uid = uid
osa.objectType = record_pb2.CHECK_SA_ON_RECORD
rq.isObjectShareAdmin.append(osa)
rs = api.communicate_rest(params, rq, 'vault/am_i_share_admin', rs_type=record_pb2.AmIShareAdmin)
if rs.isObjectShareAdmin:
if rs.isObjectShareAdmin[0].isAdmin:
is_share_admin = True
record_uid = name
except:
pass
if record_uid is None and folder_uid is None and shared_folder_uid is None:
raise CommandError('share-record', 'Enter name or uid of existing record or shared folder')
record_uids = set()
if record_uid:
record_uids.add(record_uid)
elif folder_uid:
folders = set()
folders.add(folder_uid)
if kwargs.get('recursive'):
FolderMixin.traverse_folder_tree(params, folder_uid, lambda x: folders.add(x.uid))
for uid in folders:
if uid in params.subfolder_record_cache:
record_uids.update(params.subfolder_record_cache[uid])
elif shared_folder_uid:
if not kwargs.get('recursive'):
raise CommandError('share-record', '--recursive parameter is required')
sf = api.get_shared_folder(params, shared_folder_uid)
record_uids.update((x['record_uid'] for x in sf.records))
if len(record_uids) == 0:
raise CommandError('share-record', 'There are no records to share selected')
if action == 'owner' and len(emails) > 1:
raise CommandError('share-record', 'You can transfer ownership to a single account only')
all_users = set((x.casefold() for x in emails))
if action in ('grant', 'owner'):
invited = api.load_user_public_keys(params, list(all_users), send_invites=True)
if invited:
for email in invited:
logging.warning('Share invitation has been sent to \'%s\'', email)
logging.warning('Please repeat this command when invitation is accepted.')
all_users.difference_update(invited)
all_users.intersection_update(params.key_cache.keys())
if len(all_users) == 0:
raise CommandError('share-record', 'Nothing to do.')
can_edit = kwargs.get('can_edit') or False
can_share = kwargs.get('can_share') or False
if shared_folder_uid:
api.load_records_in_shared_folder(params, shared_folder_uid, record_uids)
not_owned_records = {} if is_share_admin else None
for x in api.get_record_shares(params, record_uids, False) or []:
if not_owned_records:
record_uid = x.get('record_uid')
if record_uid:
not_owned_records[record_uid] = x
rq = record_pb2.RecordShareUpdateRequest()
existing_shares = {}
record_titles = {}
transfer_ruids = set()
for record_uid in record_uids:
if record_uid in params.record_cache:
rec = params.record_cache[record_uid]
elif not_owned_records and record_uid in not_owned_records:
rec = not_owned_records[record_uid]
elif is_share_admin:
rec = {
'record_uid': record_uid,
'shares': {
'user_permissions': [{
'username': x,
'owner': False,
'share_admin': False,
'shareable': True if action == 'revoke' else False,
'editable': True if action == 'revoke' else False,
} for x in all_users]
}
}
else:
continue
existing_shares.clear()
if 'shares' in rec:
shares = rec['shares']
if 'user_permissions' in shares:
for po in shares['user_permissions']:
existing_shares[po['username'].lower()] = po
del rec['shares']
if 'data_unencrypted' in rec:
try:
data = json.loads(rec['data_unencrypted'].decode())
if isinstance(data, dict):
if 'title' in data:
record_titles[record_uid] = data['title']
except:
pass
record_path = api.resolve_record_share_path(params, record_uid)
for email in all_users:
ro = record_pb2.SharedRecord()
ro.toUsername = email
ro.recordUid = utils.base64_url_decode(record_uid)
if record_path:
if 'shared_folder_uid' in record_path:
ro.sharedFolderUid = utils.base64_url_decode(record_path['shared_folder_uid'])
if 'team_uid' in record_path:
ro.teamUid = utils.base64_url_decode(record_path['team_uid'])
if action in {'grant', 'owner'}:
record_key = rec.get('record_key_unencrypted')
if record_key and email not in existing_shares and email in params.key_cache:
keys = params.key_cache[email]
if keys.ec:
ec_key = crypto.load_ec_public_key(keys.ec)
ro.recordKey = crypto.encrypt_ec(record_key, ec_key)
ro.useEccKey = True
elif keys.rsa:
rsa_key = crypto.load_rsa_public_key(keys.rsa)
ro.recordKey = crypto.encrypt_rsa(record_key, rsa_key)
ro.useEccKey = False
if action == 'owner':
ro.transfer = True
transfer_ruids.add(record_uid)
else:
ro.editable = can_edit
ro.shareable = can_share
if isinstance(share_expiration, int):
if share_expiration > 0:
ro.expiration = share_expiration * 1000
ro.timerNotificationType = record_pb2.NOTIFY_OWNER
elif share_expiration < 0:
ro.expiration = -1
rq.addSharedRecord.append(ro)
else:
current = existing_shares[email]
if action == 'owner':
ro.transfer = True
transfer_ruids.add(record_uid)
else:
ro.editable = True if can_edit else current.get('editable')
ro.shareable = True if can_share else current.get('shareable')
rq.updateSharedRecord.append(ro)
else:
if can_share or can_edit:
current = existing_shares[email]
ro.editable = False if can_edit else current.get('editable')
ro.shareable = False if can_share else current.get('shareable')
rq.updateSharedRecord.append(ro)
else:
rq.removeSharedRecord.append(ro)
if kwargs.get('dry_run'):
headers = ['Username', 'Record UID', 'Title', 'Share Action', 'Expiration']
table = []
for attr in ['addSharedRecord', 'updateSharedRecord', 'removeSharedRecord']:
if hasattr(rq, attr):
for obj in getattr(rq, attr):
record_uid = utils.base64_url_encode(obj.recordUid)
username = obj.toUsername
row = [username, record_uid, record_titles.get(record_uid, '')]
if attr in ['addSharedRecord', 'updateSharedRecord']:
if obj.transfer:
row.append('Transfer Ownership')
elif obj.editable or obj.shareable:
if obj.editable and obj.shareable:
row.append('Can Edit & Share')
elif obj.editable:
row.append('Can Edit')
else:
row.append('Can Share')
else:
row.append('Read Only')
else:
row.append('Remove Share')
if obj.expiration > 0:
dt = datetime.datetime.fromtimestamp(obj.expiration//1000)
row.append(str(dt))
else:
row.append(None)
table.append(row)
dump_report_data(table, headers, row_number=True, group_by=0)
return
while len(rq.addSharedRecord) > 0 or len(rq.updateSharedRecord) > 0 or len(rq.removeSharedRecord) > 0:
rq1 = record_pb2.RecordShareUpdateRequest()
left = 990
if left > 0 and len(rq.addSharedRecord) > 0:
rq1.addSharedRecord.extend(rq.addSharedRecord[0:left])
added = len(rq1.addSharedRecord)
del rq.addSharedRecord[0:added]
left -= added
if left > 0 and len(rq.updateSharedRecord) > 0:
rq1.updateSharedRecord.extend(rq.updateSharedRecord[0:left])
added = len(rq1.updateSharedRecord)
del rq.updateSharedRecord[0:added]
left -= added
if left > 0 and len(rq.removeSharedRecord) > 0:
rq1.removeSharedRecord.extend(rq.removeSharedRecord[0:left])
added = len(rq1.removeSharedRecord)
del rq.removeSharedRecord[0:added]
left -= added
rs = api.communicate_rest(params, rq1, 'vault/records_share_update', rs_type=record_pb2.RecordShareUpdateResponse)
for attr in ['addSharedRecordStatus', 'updateSharedRecordStatus', 'removeSharedRecordStatus']:
if hasattr(rs, attr):
statuses = getattr(rs, attr)
for status_rs in statuses:
record_uid = utils.base64_url_encode(status_rs.recordUid)
status = status_rs.status
email = status_rs.username
if status == 'success':
verb = 'granted to' if attr == 'addSharedRecordStatus' else 'changed for' if attr == 'updateSharedRecordStatus' else 'revoked from'
logging.info('Record \"%s\" access permissions has been %s user \'%s\'', record_uid, verb, email)
else:
verb = 'grant' if attr == 'addSharedRecordStatus' else 'change' if attr == 'updateSharedRecordStatus' else 'revoke'
logging.info('Failed to %s record \"%s\" access permissions for user \'%s\': %s', record_uid, verb, email, status_rs.message)
if transfer_ruids:
from keepercommander.breachwatch import BreachWatch
BreachWatch.save_reused_pw_count(params)
class ShareReportCommand(Command):
def get_parser(self):
return share_report_parser
@staticmethod
def sf_report(params, out=None, fmt=None, show_team_users=False):
def get_share_info(share_target, name_key): # type: (Dict[str, Any], str) -> Dict[str, str]
manage_users = share_target.get('manage_users')
manage_records = share_target.get('manage_records')
if not manage_users and not manage_records:
permissions = "No User Permissions"
elif not manage_users and manage_records:
permissions = "Cam Manage Records"
elif manage_users and not manage_records:
permissions = "Can Manage Users"
else:
permissions = "Can Manage Users & Records"
share = {
'name': share_target.get(name_key),
'permissions': permissions
}
return share
def get_username(user_uid, users): # type: (int, Iterable[Dict[str, Any]]) -> str
for u in users:
if user_uid == u.get('enterprise_user_id'):
return u.get('username')
def get_team_shares(share_target):
t_shares = [share_target]
if params.enterprise and show_team_users:
e_team_users = params.enterprise.get('team_users') or []