create_shared.py 19.2 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
20

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


class SharedAccount:

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

    def create_box(self):
        try:
33
34
35
36
            self.logger.info(
                'Creating Box account',
                extra={'entity': self.account}
            )
37
38
39
40
41
            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
42
            self.logger.error(e, extra={'entity': self.account})
43
44
            exit(2)
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
45
            self.logger.error(e, extra={'entity': self.account})
46
47
48
49
            exit(2)

        try:
            if len(self.full_name) > 50:
Rob Carleski's avatar
Rob Carleski committed
50
                self.logger.warning(
51
52
53
54
55
56
57
                    '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,
58
                tracking_codes=[{
59
60
                    'name': 'account_type',
                    'value': 'shared'
61
                }]
62
            )
Rob Carleski's avatar
Rob Carleski committed
63
64
65
66
67
68
69
70
71
72
        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
73

Rob Carleski's avatar
Rob Carleski committed
74
        try:
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
            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
122
                            self.logger.warning(
123
124
125
126
127
128
129
                                '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
130
            self.logger.error(e, extra={'entity': self.account})
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154

    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
155
            self.logger.error(e, extra={'entity': self.account})
156
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
157
            self.logger.error(e, extra={'entity': self.account})
158
159
160

    def create_google(self):
        try:
161
162
163
164
            self.logger.info(
                'Creating Google account',
                extra={'entity': self.account}
            )
165
166
167
168
169
170
171
172
173
174
175
176
177
            cmd([
                self.config['google']['gam_command'],
                'create',
                'user',
                self.account,
                'firstname',
                self.first_name,
                'lastname',
                self.last_name,
                'password',
                self.password,
                'org',
                'Department accounts'
178
            ], stderr=devnull)
179
        except CalledProcessError as e:
180
181
182
183
184
185
186
187
188
189
190
191
            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})
192
193
194
195
196

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

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

    def set_up_mcommunity_group(self):
201
202
203
204
205
206
        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
207
        try:
208
209
210
211
212
            self.logger.info(
                'Checking Mcommunity for associated group',
                extra={'entity': self.account}
            )
            client.fetch_group(self.account)
213
214
215
        except ValueError as e:
            self.logger.info(e, extra={'entity': self.account})
            exit(2)
216
217
218
        except Exception as e:
            self.logger.info(e, extra={'entity': self.account})

219
220
221
222
        if hasattr(client, 'group_data'):
            self.logger.info(
                'Found associated MCommunity group',
                extra={'entity': self.account}
223
            )
224
225
226
227
228
229
230
231
232
233
            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
234
235
                else:
                    needs_update = True
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

            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
256
257
        else:
            try:
258
259
260
261
262
263
                if len(self.owners) == 0:
                    self.logger.error(
                        'No owners provided for new MCommunity group.',
                        extra={'entity': self.account}
                    )
                    exit(2)
264
265
266
267
268
                self.logger.info(
                    'Reserving new Mcommunity group',
                    extra={'entity': self.account}
                )
                client.reserve_group(self.account)
Rob Carleski's avatar
Rob Carleski committed
269
270
271
272
                self.logger.info(
                    'Fetching new Mcommunity group',
                    extra={'entity': self.account}
                )
273
                client.fetch_group(self.account)
274
275
276
            except Exception as e:
                self.logger.info(e, extra={'entity': self.account})
                exit(2)
277
278

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

        try:
288
289
290
291
            self.logger.info(
                'Updating Mcommunity group membership',
                extra={'entity': self.account}
            )
292
            if self.service in ['google', 'both']:
293
294
295
296
297
298
299
300
301
302
303
                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(
304
305
                self.config['mcommunity']['api_control_group']
            )
306
            client.update_group_owners()
307
        except Exception as e:
Rob Carleski's avatar
Rob Carleski committed
308
            self.logger.warning(e, extra={'entity': self.account})
309
310
311
312
313
314
315

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

    def set_kerberos_password(self):
        try:
316
317
318
319
            self.logger.info(
                'Creating kerberos principal',
                extra={'entity': self.account}
            )
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
            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:
336
            self.logger.warning(e, extra={'entity': self.account})
337
338

    def upload_and_share_password(self):
339
        passFilePath = '{}/{}-passwd.txt'.format(
340
341
342
            self.config['general']['data_dir'],
            self.account
        )
Rob Carleski's avatar
Rob Carleski committed
343
        exp_time = datetime.today() + timedelta(days=10)
344
        with open(passFilePath, 'w') as passwordFile:
Rob Carleski's avatar
Rob Carleski committed
345
346
347
348
349
350
351
352
353
354
355
            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))
356
357
358
359
360
361
362
363
364
365
366

        upload_output = cmd([
            self.config['google']['gam_command'],
            'user',
            self.config['google']['admin_account'],
            'add',
            'drivefile',
            'localfile',
            passFilePath,
            'parentname',
            'Shared Account Passwords'
367
        ], stderr=devnull)
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
        file_id = re.search(
            r'.*\((.*)\)',
            upload_output.decode('UTF-8')
        ).groups()[0]

        for owner in self.owners:
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    self.config['google']['admin_account'],
                    'add',
                    'drivefileacl',
                    file_id,
                    'user',
                    owner,
                    'role',
                    'reader'
                ])
Rob Carleski's avatar
Rob Carleski committed
387
388
389
390
391
            except CalledProcessError:
                self.logger.warning(
                    'Error sharing password file with {}'.format(owner),
                    extra={'entity': self.account}
                )
392
393
394
395
396
397
                continue

        os.remove(passFilePath)
        return file_id

    def create_extra_attr(self):
Rob Carleski's avatar
Rob Carleski committed
398
        if self.first_name and self.last_name:
Rob Carleski's avatar
Rob Carleski committed
399
400
401
402
            self.full_name = '{} {}'.format(
                self.first_name,
                self.last_name
            )
Rob Carleski's avatar
Rob Carleski committed
403
        else:
404
            split = re.split(r'[\-\_\.\s]+', self.account)
405
406
407
408
409
410
411
            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)
412
413
414
415
416
417
418
            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
            )

419
420
421
422
423
424
        self.account = re.sub(r'[^\w-]', '.', self.account).lower().strip()
        self.group_alias = re.sub(
            r'[^\w-]',
            ' ',
            self.full_name
        ).replace('_', ' ').strip()
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
        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',
465
        help='Uniqname(s) of shared account owner(s)',
466
467
        nargs='+',
        default={}
468
469
    )
    parser.add_argument(
470
        '--service',
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
        '-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
508
    logger = logging.getLogger(__name__)
Rob Carleski's avatar
Rob Carleski committed
509
    logger.setLevel(logging.INFO)
510
511
512
513
514
515
516
517
518
519
520
521

    # 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()
522
523
524
525
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
526
527
528
    ch.setFormatter(formatter)
    logger.addHandler(ch)

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

533
    sa = SharedAccount(vars(args), config)
534
535
536
537
538
539
    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()
540
    pass_file_id = sa.upload_and_share_password()
541
542
543
544
545
546
547

    header_text = '''
Hello,

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

548
https://docs.google.com/a/{}/file/d/{}
549
550
551
552
553
554

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:
555
556
557
- Display Name: {}
- Username: {}
- Email Address: {}
558
'''.format(
559
560
        config['google']['domain'],
        pass_file_id,
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
        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,
581
582
        sa.box_text if hasattr(sa, 'box_text') else '',
        sa.google_text if hasattr(sa, 'google_text') else '',
583
584
585
586
587
588
        footer_text
    )


if __name__ == '__main__':
    main()