create_shared.py 19.8 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
7
8
9
import argparse
import boxsdk
import kadmin
import logging
import logging.handlers
import mcommunity
import os
import re
Rob Carleski's avatar
Rob Carleski committed
10
import string
11
12
13
import yaml

from boxsdk.object.collaboration import CollaborationRole
Rob Carleski's avatar
Rob Carleski committed
14
15
16
from datetime import datetime
from datetime import timedelta
from secrets import choice
17
18
from subprocess import check_output as cmd
from subprocess import CalledProcessError
19
from subprocess import STDOUT
20
21

devnull = open(os.devnull, 'w')
22
23
24
25
26
27
28


class SharedAccount:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
Rob Carleski's avatar
Rob Carleski committed
29
        self.logger = logging.getLogger(__name__)
30
        self.create_extra_attr()
31
32
33

    def create_box(self):
        try:
34
35
36
37
            self.logger.info(
                'Creating Box account',
                extra={'entity': self.account}
            )
38
39
40
41
42
            auth = boxsdk.JWTAuth.from_settings_file(
                self.config['box']['auth_file']
            )
            boxClient = boxsdk.Client(auth)
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
43
            self.logger.error(e, extra={'entity': self.account})
44
45
            exit(2)
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
46
            self.logger.error(e, extra={'entity': self.account})
47
48
49
50
            exit(2)

        try:
            if len(self.full_name) > 50:
Rob Carleski's avatar
Rob Carleski committed
51
                self.logger.warning(
52
53
54
55
56
57
58
                    'Full name attribute for user exceeds limit. Truncating.',
                    extra={'entity': self.account}
                )
            boxAccount = boxClient.create_user(
                name=self.full_name[:50],
                login=self.email,
                space_amount=-1,
59
                tracking_codes=[{
60
61
                    'name': 'account_type',
                    'value': 'shared'
62
                }]
63
            )
Rob Carleski's avatar
Rob Carleski committed
64
65
66
67
68
69
70
71
72
73
        except boxsdk.exception.BoxAPIException as e:
            if e.status in [409, 403]:
                self.logger.info(
                    e.message,
                    extra={'entity': self.account}
                )
                return
            else:
                self.logger.error(e, extra={'entity': self.account})
                return
74

Rob Carleski's avatar
Rob Carleski committed
75
        try:
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
            boxAccount.update_info({'is_sync_enabled': False})

            self.shared_box_folder = boxClient.as_user(
                boxAccount
            ).folder(
                0
            ).create_subfolder(
                self.full_name
            )

            self.box_text = '''
Box-Specific Information:
 - The ability to use Box Sync with shared accounts is disabled by default,
but allowed in certain circumstances; if you need this, please reply to this
message to discuss. Syncing the shared folder in your individual account is
always allowed.

 - Files placed in shared account folders are owned by the shared account.

 - To learn more about using your shared account, visit the Shared U-M Box
Accounts section of the M+Box support site.

(http://www.itcs.umich.edu/storage/box/shared-accounts.php)

'''
            if self.secure:
                self.shared_box_folder.update_info({
                    'can_non_owners_invite': False,
                    'allowed_shared_link_access_levels': ['collaborators']
                })
                self.box_text += '''
 - Settings appropriate for sensitive data have been applied to this folder.
'''

            self.upload_box_info_file()

            for owner in self.owners:
                search = boxClient.users(filter_term=owner)
                for _ in search:
                    login = _['login'].split('@')[0].lower()
                    if owner.lower() == login:
                        try:
                            self.shared_box_folder.collaborate(
                                _,
                                CollaborationRole.CO_OWNER
                            )
                        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
123
                            self.logger.warning(
124
125
126
127
128
129
130
                                'Unable to add {} as Box collaborator'.format(
                                    _
                                 ),
                                extra={'entity': self.account}
                            )
                        break
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
131
            self.logger.error(e, extra={'entity': self.account})
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

    def upload_box_info_file(self):
        try:
            readme = '{}/{}-{}'.format(
                self.config['general']['data_dir'],
                self.account,
                'README.txt'
            )
            with open(readme, 'w+') as stream:
                content = '''
The folder "{}" is owned by the shared account "{}".

The initial co-owners on this folder are based on the owners listed on the
request form at the time this folder was created.

The co-owners and members will NOT be kept in sync with MCommunity.

f you have any questions please contact the ITS Service Center:

http://its.umich.edu/help/'''.format(self.full_name, self.email)
                stream.write(content)
            self.shared_box_folder.upload(readme)
            os.remove(readme)
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
156
            self.logger.error(e, extra={'entity': self.account})
157
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
158
            self.logger.error(e, extra={'entity': self.account})
159
160
161

    def create_google(self):
        try:
162
163
164
165
            self.logger.info(
                'Creating Google account',
                extra={'entity': self.account}
            )
166
167
168
169
170
171
172
173
174
175
176
177
178
            cmd([
                self.config['google']['gam_command'],
                'create',
                'user',
                self.account,
                'firstname',
                self.first_name,
                'lastname',
                self.last_name,
                'password',
                self.password,
                'org',
                'Department accounts'
179
            ], stderr=devnull)
180
        except CalledProcessError as e:
181
182
183
184
185
186
187
188
189
190
191
192
            if e.returncode == 144:
                self.logger.info(
                    'Invalid data provided to Google account creation call',
                    extra={'entity': self.account}
                )
            elif e.returncode == 153:
                self.logger.info(
                    'Account already exists in Google',
                    extra={'entity': self.account}
                )
            else:
                self.logger.error(e, extra={'entity': self.account})
193
194
195
196
197

        self.google_text = '''
Google-Specific Information:
- For information on using this account, please check the following URL:

198
https://documentation.its.umich.edu/node/339/
199
200
201
'''

    def set_up_mcommunity_group(self):
202
203
204
205
206
207
        client = mcommunity.Client(self.config['mcommunity'])
        controllerCn = client._create_entity_ldap(
            self.config['mcommunity']['api_control_group']
        )
        ext_addr = self.account.lower() + '@go.itd.umich.edu'
        needs_update = False
208
        try:
209
210
211
212
213
            self.logger.info(
                'Checking Mcommunity for associated group',
                extra={'entity': self.account}
            )
            client.fetch_group(self.account)
214
215
216
        except ValueError as e:
            self.logger.info(e, extra={'entity': self.account})
            exit(2)
217
218
219
        except Exception as e:
            self.logger.info(e, extra={'entity': self.account})

220
221
222
223
        if hasattr(client, 'group_data'):
            self.logger.info(
                'Found associated MCommunity group',
                extra={'entity': self.account}
224
            )
225
226
227
228
229
230
231
232
233
234
            for owner in self.owners:
                ownerDn = client._create_entity_ldap(owner).lower()
                if ownerDn not in client.group_data['ownerDn']:
                    needs_update = True
                    break

            if self.service in ['google', 'both']:
                if type(client.group_data['memberExternalRaw']) is list:
                    if ext_addr not in client.group_data['memberExternalRaw']:
                        needs_update = True
Rob Carleski's avatar
Rob Carleski committed
235
236
                else:
                    needs_update = True
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

            if needs_update:
                self.logger.info(
                    'Mcommunity group needs updating',
                    extra={'entity': self.account}
                )
                if controllerCn not in client.group_data['ownerDn']:
                    if not self.take_group_ownership(self.account):
                        self.logger.error(
                            'Failed to obtain group ownership',
                            extra={'entity': self.account}
                        )
                        exit(2)
                    client.fetch_group(self.account)
            else:
                self.logger.info(
                    'Mcommunity group does not need an update',
                    extra={'entity': self.account}
                )
                return
257
258
        else:
            try:
259
260
261
262
263
264
                if len(self.owners) == 0:
                    self.logger.error(
                        'No owners provided for new MCommunity group.',
                        extra={'entity': self.account}
                    )
                    exit(2)
265
266
267
268
269
                self.logger.info(
                    'Reserving new Mcommunity group',
                    extra={'entity': self.account}
                )
                client.reserve_group(self.account)
Rob Carleski's avatar
Rob Carleski committed
270
271
272
273
                self.logger.info(
                    'Fetching new Mcommunity group',
                    extra={'entity': self.account}
                )
274
                client.fetch_group(self.account)
275
276
277
            except Exception as e:
                self.logger.info(e, extra={'entity': self.account})
                exit(2)
278
279

        try:
Rob Carleski's avatar
Rob Carleski committed
280
281
282
283
            self.logger.info(
                'Adding Mcommunity group alias',
                extra={'entity': self.account}
            )
284
            client.update_group_aliases(self.group_alias)
Rob Carleski's avatar
Rob Carleski committed
285
286
287
288
        except Exception as e:
            self.logger.warning(e, extra={'entity': self.account})

        try:
289
290
291
292
            self.logger.info(
                'Updating Mcommunity group membership',
                extra={'entity': self.account}
            )
293
            if self.service in ['google', 'both']:
294
295
296
297
298
299
300
301
302
303
304
                client.add_group_members(ext_addr)
            client.remove_group_members(
                self.config['mcommunity']['api_control_group']
            )
            client.update_group_members()
            self.logger.info(
                'Updating Mcommunity group ownership',
                extra={'entity': self.account}
            )
            client.add_group_owners(self.owners)
            client.remove_group_owners(
305
306
                self.config['mcommunity']['api_control_group']
            )
307
            client.update_group_owners()
308
        except Exception as e:
Rob Carleski's avatar
Rob Carleski committed
309
            self.logger.warning(e, extra={'entity': self.account})
310
311
312
313
314
315
316

    def take_group_ownership(self, group):
        input('Add api controller as group owner, then press enter.')
        return True

    def set_kerberos_password(self):
        try:
317
318
319
320
            self.logger.info(
                'Creating kerberos principal',
                extra={'entity': self.account}
            )
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
            admin = '{}@{}'.format(
                self.config['kerberos']['admin'],
                self.config['kerberos']['realm'].upper()
            )
            kadm = kadmin.init_with_keytab(
                admin,
                self.config['kerberos']['keytab']
            )
            kadm.ank(
                '{}@{}'.format(
                    self.account,
                    self.config['kerberos']['realm'].upper()
                ),
                self.password
            )
        except kadmin.KAdminError as e:
337
            self.logger.warning(e, extra={'entity': self.account})
338
339

    def upload_and_share_password(self):
340
        passFilePath = '{}/{}-passwd.txt'.format(
341
342
343
            self.config['general']['data_dir'],
            self.account
        )
Rob Carleski's avatar
Rob Carleski committed
344
        exp_time = datetime.today() + timedelta(days=10)
345
        with open(passFilePath, 'w') as passwordFile:
Rob Carleski's avatar
Rob Carleski committed
346
347
348
349
350
351
352
353
354
355
356
            passwordFile.write('''
For security, this file will expire automatically on {}. Please store
this password somewhere safe. ITS has best practice recommendations for
doing so at the following URL:

https://safecomputing.umich.edu/protect-yourself/manage-your-passwords

The password for your requested shared account is:

{}
'''.format(exp_time.strftime('%Y-%m-%d'), self.password))
357
358
359
360
361
362
363
364
365
366
367

        upload_output = cmd([
            self.config['google']['gam_command'],
            'user',
            self.config['google']['admin_account'],
            'add',
            'drivefile',
            'localfile',
            passFilePath,
            'parentname',
            'Shared Account Passwords'
368
        ], stderr=devnull)
369
370
371
372
373
374
        file_id = re.search(
            r'.*\((.*)\)',
            upload_output.decode('UTF-8')
        ).groups()[0]

        for owner in self.owners:
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
            try:
                whatis = cmd([
                    self.config['google']['gam_command'],
                    'whatis',
                    owner
                ], stderr=STDOUT)
            except CalledProcessError:
                self.logger.warning(
                    '{} does not seem to exist in Google.'.format(owner),
                    extra={'entity': self.account}
                )
                continue

            if b'is a user' in whatis:
                entity_type = 'user'
            elif b'is a group' in whatis:
                entity_type = 'group'

393
394
395
396
397
398
399
400
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    self.config['google']['admin_account'],
                    'add',
                    'drivefileacl',
                    file_id,
401
                    entity_type,
402
403
404
                    owner,
                    'role',
                    'reader'
405
                ], stderr=STDOUT)
Rob Carleski's avatar
Rob Carleski committed
406
407
            except CalledProcessError:
                self.logger.warning(
408
                    'Unable to share password with {}'.format(owner),
Rob Carleski's avatar
Rob Carleski committed
409
410
                    extra={'entity': self.account}
                )
411
412
413
414
415
416
                continue

        os.remove(passFilePath)
        return file_id

    def create_extra_attr(self):
Rob Carleski's avatar
Rob Carleski committed
417
        if self.first_name and self.last_name:
Rob Carleski's avatar
Rob Carleski committed
418
419
420
421
            self.full_name = '{} {}'.format(
                self.first_name,
                self.last_name
            )
Rob Carleski's avatar
Rob Carleski committed
422
        else:
423
            split = re.split(r'[\-\_\.\s]+', self.account)
424
425
426
427
428
429
430
            if len(split) == 1:
                self.logger.error(
                    'Cannot create first and last name from given account.'
                    ' Rerun script specifying first and last names.',
                    extra={'entity': self.account}
                )
                exit(2)
431
432
433
434
435
436
437
            self.first_name = ' '.join(split[:len(split)//2]).title()
            self.last_name = ' '.join(split[len(split)//2:]).title()
            self.full_name = '{} {}'.format(
                self.first_name,
                self.last_name
            )

438
439
440
441
442
443
        self.account = re.sub(r'[^\w-]', '.', self.account).lower().strip()
        self.group_alias = re.sub(
            r'[^\w-]',
            ' ',
            self.full_name
        ).replace('_', ' ').strip()
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
        self.email = '{}@{}'.format(
            self.account,
            self.config['google']['domain']
        )


def main():
    helptext = '''examples:
        collab-create-shared -a collab-testing -p pass12word -o mlkjr moliere
        collab-create-shared -a collab-testing -f collab -l testing -t google
            -p pass12word -o mlkjr moliere -s
        collab-create-shared --account collab-testing --password pass12word
            --owners mlkjr moliere
        collab-create-shared --acount collab-testing --password pass12word
            --owners mlkdir moliere --first_name collab --last_name testing
            --type box --secure

        Note: If first and last names are not provided, they will be set
            automatically using common delimiters
        '''

    parser = argparse.ArgumentParser(
        description='Creates shared accounts in collab services',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--account',
        '-a',
        help='The account name to use.',
        required=True
    )
    parser.add_argument(
        '--password',
        '-p',
        help='The password to use for the account',
    )
    parser.add_argument(
        '--owners',
        '-o',
484
        help='Uniqname(s) of shared account owner(s)',
485
486
        nargs='+',
        default={}
487
488
    )
    parser.add_argument(
489
        '--service',
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
        '-s',
        help='The type of account(s) to create',
        choices=[
            'google',
            'box',
            'both'
        ],
        default='both'
    )
    parser.add_argument(
        '--first_name',
        '-f',
        help='The first name to use for the account',
    )
    parser.add_argument(
        '--last_name',
        '-l',
        help='The last name to use for the account',
    )
    parser.add_argument(
        '--secure',
        help='Secure the account for sensitive data',
        action='store_true'
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use for Google operations',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

    # Open the CAK Config
    with open(args.config) as stream:
        config = yaml.load(stream, Loader=yaml.BaseLoader)

    # Get the root logger and set the debug level
Rob Carleski's avatar
Rob Carleski committed
527
    logger = logging.getLogger(__name__)
Rob Carleski's avatar
Rob Carleski committed
528
    logger.setLevel(logging.INFO)
529
530
531
532
533
534
535
536
537
538
539
540

    # Create a syslog handler, set format, and associate.
    sh = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=config['general']['log_facility']
    )
    formatter = logging.Formatter(config['general']['log_format'])
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    # Create a console handler, set format, and associate.
    ch = logging.StreamHandler()
541
542
543
544
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
545
546
547
    ch.setFormatter(formatter)
    logger.addHandler(ch)

Rob Carleski's avatar
Rob Carleski committed
548
549
550
551
    if not args.password:
        pool = string.ascii_letters + string.digits + '!@#$%&*'
        args.password = ''.join(choice(pool) for i in range(12))

552
    sa = SharedAccount(vars(args), config)
553
554
555
556
557
558
    sa.set_up_mcommunity_group()
    sa.set_kerberos_password()
    if sa.service in ['box', 'both']:
        sa.create_box()
    if sa.service in ['google', 'both']:
        sa.create_google()
559
    pass_file_id = sa.upload_and_share_password()
560
561
562
563
564
565
566

    header_text = '''
Hello,

Your request has been completed. The password for your shared account
can be found at the following link:

567
https://docs.google.com/a/{}/file/d/{}
568
569
570
571
572
573

We recommend using a Chrome incognito window or separate browser to log
into your shared account. Please see below for more information about the
shared account created per your request:

General Account Information:
574
575
576
- Display Name: {}
- Username: {}
- Email Address: {}
577
'''.format(
578
579
        config['google']['domain'],
        pass_file_id,
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
        sa.full_name,
        sa.account,
        sa.email,
    )

    footer_text = '''
Single-Sign On is used for both Box and Google, and the method of changing
the password is the same for both. For information on changing the password,
please check the documentation found here:

https://documentation.its.umich.edu/node/339/#password

I will be closing this ticket now, as your request has been completed, but
feel free to reply back to this email if you have any questions or concerns
about your new account and the ticket will be re-opened.
'''

    print(
        '========== CANNED TEXT ==========',
        header_text,
600
601
        sa.box_text if hasattr(sa, 'box_text') else '',
        sa.google_text if hasattr(sa, 'google_text') else '',
602
603
604
605
606
607
        footer_text
    )


if __name__ == '__main__':
    main()