create_shared.py 18.1 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
28


class SharedAccount:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
        self.create_extra_attr()
Rob Carleski's avatar
Rob Carleski committed
29
        self.logger = logging.getLogger(__name__)
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 Exception as e:
            self.logger.info(e, extra={'entity': self.account})

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

            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
253
254
        else:
            try:
255
256
257
258
259
                self.logger.info(
                    'Reserving new Mcommunity group',
                    extra={'entity': self.account}
                )
                client.reserve_group(self.account)
Rob Carleski's avatar
Rob Carleski committed
260
261
262
263
                self.logger.info(
                    'Fetching new Mcommunity group',
                    extra={'entity': self.account}
                )
264
                client.fetch_group(self.account)
265
266
267
            except Exception as e:
                self.logger.info(e, extra={'entity': self.account})
                exit(2)
268
269

        try:
Rob Carleski's avatar
Rob Carleski committed
270
271
272
273
274
            self.logger.info(
                'Adding Mcommunity group alias',
                extra={'entity': self.account}
            )
            client.update_group_aliases(self.full_name)
275
276
277
278
            self.logger.info(
                'Updating Mcommunity group membership',
                extra={'entity': self.account}
            )
279
            if self.service in ['google', 'both']:
280
281
282
283
284
285
286
287
288
289
290
                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(
291
292
                self.config['mcommunity']['api_control_group']
            )
293
            client.update_group_owners()
294
        except Exception as e:
Rob Carleski's avatar
Rob Carleski committed
295
            self.logger.warning(e, extra={'entity': self.account})
296
297
298
299
300
301
302

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

    def set_kerberos_password(self):
        try:
303
304
305
306
            self.logger.info(
                'Creating kerberos principal',
                extra={'entity': self.account}
            )
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
            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:
323
            self.logger.warning(e, extra={'entity': self.account})
324
325

    def upload_and_share_password(self):
326
        passFilePath = '{}/{}-passwd.txt'.format(
327
328
329
            self.config['general']['data_dir'],
            self.account
        )
Rob Carleski's avatar
Rob Carleski committed
330
        exp_time = datetime.today() + timedelta(days=10)
331
        with open(passFilePath, 'w') as passwordFile:
Rob Carleski's avatar
Rob Carleski committed
332
333
334
335
336
337
338
339
340
341
342
            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))
343
344
345
346
347
348
349
350
351
352
353

        upload_output = cmd([
            self.config['google']['gam_command'],
            'user',
            self.config['google']['admin_account'],
            'add',
            'drivefile',
            'localfile',
            passFilePath,
            'parentname',
            'Shared Account Passwords'
354
        ], stderr=devnull)
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
        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'
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
375
                self.logger.warning(e.output, extra={'entity': self.account})
376
377
378
379
380
381
382
                continue

        os.remove(passFilePath)
        return file_id

    def create_extra_attr(self):
        try:
Rob Carleski's avatar
Rob Carleski committed
383
384
385
386
            self.full_name = '{} {}'.format(
                self.first_name,
                self.last_name
            )
387
        except TypeError:
388
389
390
391
392
393
394
395
            split = re.split(r'[\-\_\.\s]+', self.account)
            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
            )

396
397
        self.account = re.sub(r'[^\w_-]', '.', self.account).lower().strip()

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
        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',
        help='Owners for the shared account',
        nargs='+'
    )
    parser.add_argument(
442
        '--service',
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
        '-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
480
    logger = logging.getLogger(__name__)
Rob Carleski's avatar
Rob Carleski committed
481
    logger.setLevel(logging.INFO)
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497

    # 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()
    formatter = logging.Formatter(config['general']['console_format'])
    ch.setFormatter(formatter)
    logger.addHandler(ch)

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

502
    sa = SharedAccount(vars(args), config)
503
504
505
506
507
508
    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()
509
    pass_file_id = sa.upload_and_share_password()
510
511
512
513
514
515
516

    header_text = '''
Hello,

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

517
https://docs.google.com/a/{}/file/d/{}
518
519
520
521
522
523

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:
524
525
526
- Display Name: {}
- Username: {}
- Email Address: {}
527
'''.format(
528
529
        config['google']['domain'],
        pass_file_id,
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
        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,
550
551
        sa.box_text if hasattr(sa, 'box_text') else '',
        sa.google_text if hasattr(sa, 'google_text') else '',
552
553
554
555
556
557
        footer_text
    )


if __name__ == '__main__':
    main()