Note: The default ITS GitLab runner is a shared resource and is subject to slowdowns during heavy usage.
You can run your own GitLab runner that is dedicated just to your group if you need to avoid processing delays.

reset_shared.py 10.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
10
import string
11
12
import yaml

13
14
from .core import arg_prompt
from secrets import choice
15
16
17
18
19
20
21
from subprocess import check_output as cmd
from subprocess import CalledProcessError
from subprocess import STDOUT


class SharedAccount():

22
23
    def __init__(self, args, config):
        self.__dict__.update(args)
24
25
26
        self.config = config
        self.box_exists = False
        self.google_exists = False
Rob Carleski's avatar
Rob Carleski committed
27
        self.logger = logging.getLogger(__name__)
28
29
        self.groupname = re.sub(r'[\_\.]', ' ', self.account.strip()).lower()
        self.username = re.sub(r'[\_\s]', '.', self.account.strip()).lower()
30
31
32
33
34
35
36

    def check_box(self):
        try:
            auth = boxsdk.JWTAuth.from_settings_file(
                self.config['box']['auth_file']
            )
            boxClient = boxsdk.Client(auth)
37
            boxUsers = boxClient.users(filter_term=self.username)
38
39
            for _ in boxUsers:
                login = _['login'].split('@')[0]
40
                if self.username.lower() == login.lower():
41
42
43
44
                    self.box_exists = True
                    break
            return False
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
45
            self.logger.error(e, extra={'entity': self.account})
46
        except boxsdk.exception.BoxAPIException as e:
Rob Carleski's avatar
Rob Carleski committed
47
            self.logger.error(e, extra={'entity': self.account})
48
49
50
51
52
53

    def check_google(self):
        try:
            output = cmd([
                self.config['google']['gam_command'],
                'whatis',
54
                self.username,
55
56
57
58
59
60
61
62
63
64
65
                'userview'
                ], stderr=STDOUT
            )
            if 'is a user' in output.decode('UTF-8'):
                self.google_exists = True
            return False
        except CalledProcessError:
            return False

    def check_mcommunity(self):
        try:
66
67
68
69
            client = mcommunity.MCommClient(
                self.config['mcommunity']['client_id'],
                self.config['mcommunity']['secret']
            )
70
            self.mcomm_group = client.group(self.groupname)
Rob Carleski's avatar
Rob Carleski committed
71
            assert self.mcomm_group.dn
72
        except mcommunity.core.MCommError as e:
Rob Carleski's avatar
Rob Carleski committed
73
            self.logger.error(e, extra={'entity': self.account})
74
            exit(2)
Rob Carleski's avatar
Rob Carleski committed
75
76
77
78
79
80
        except AssertionError:
            self.logger.error(
                'Unable to find matching group in MCommunity',
                extra={'entity': self.account}
            )
            exit(2)
81
82
83
84
85
86
87
88
89
90
91

    def set_kerberos_password(self):
        try:
            admin = '{}@{}'.format(
                self.config['kerberos']['admin'],
                self.config['kerberos']['realm'].upper()
            )
            kadm = kadmin.init_with_keytab(
                admin,
                self.config['kerberos']['keytab']
            )
Rob Carleski's avatar
Rob Carleski committed
92
            principal = '{}@{}'.format(
93
                self.username,
Rob Carleski's avatar
Rob Carleski committed
94
95
                self.config['kerberos']['realm'].upper()
            )
96
97
98
99
            princ = kadm.getprinc(principal)
            if not princ:
                self.logger.warning(
                    'Kerberos principal does not exist. Creating.',
100
                    extra={'entity': self.username}
101
102
103
104
                )
                kadm.addprinc(principal, self.password)
            else:
                princ.change_password(self.password)
105
        except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
106
            self.logger.error(e, extra={'entity': self.account})
107
108
            exit(2)
        except kadmin.KAdminError as e:
109
            self.logger.error(e, extra={'entity': self.account})
110
111
112
113
114
115
116
117
            exit(2)

    def set_google_password(self):
        try:
            cmd([
                self.config['google']['gam_command'],
                'update',
                'user',
118
                self.username,
119
120
121
122
123
                'password',
                self.password
            ], stderr=STDOUT
            )
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
124
            self.logger.error(e.output, extra={'entity': self.account})
125
126
127

    def upload_and_share_password(self):
        try:
128
            passFilePath = '{}/{}-passwd.txt'.format(
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
                self.config['general']['data_dir'],
                self.account
            )

            with open(passFilePath, 'w') as passwordFile:
                passwordFile.write(self.password)

            upload_output = cmd([
                self.config['google']['gam_command'],
                'user',
                self.config['google']['admin_account'],
                'add',
                'drivefile',
                'localfile',
                passFilePath,
                'parentname',
                'Shared Account Passwords'
146
            ], stderr=STDOUT)
147
148
149
150
151
            self.file_id = re.search(
                r'.*\((.*)\)',
                upload_output.decode('UTF-8')
            ).groups()[0]
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
152
            self.logger.error(e.output, extra={'entity': self.account})
153

154
        for owner in self.mcomm_group.owners:
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
            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'

173
174
175
176
177
178
179
180
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    self.config['google']['admin_account'],
                    'add',
                    'drivefileacl',
                    self.file_id,
181
                    entity_type,
182
183
184
                    owner,
                    'role',
                    'reader'
185
                ], stderr=STDOUT)
186
            except CalledProcessError:
Rob Carleski's avatar
Rob Carleski committed
187
                self.logger.warning(
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
                    'Unable to share password with {}'.format(owner),
                    extra={'entity': self.account}
                )
                continue

        os.remove(passFilePath)

    def print_canned_text(self):
        print('''
Hello,

The password for your shared account has been changed. The new password for
this account is stored in your Google Drive space, and can be found at the
following link:

203
https://docs.google.com/a/{}/file/d/{}.
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

Please note that this file will expire automatically in ten (10) days, and
has been shared with any additional owners of the MCommunity group associated
with this account. Coordinate with other account owners before making changes
to this password.

For information on setting this password to a value of your choosing, please
see our documentation found at the following link:

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

If you are still unable to log into your shared account, or if you have any
additional questions or concerns, simply reply to this message and your request
will be automatically re-opened.

219
'''.format(self.config['google']['domain'], self.file_id))
220
221
222
223
224
225
226
227
228
229


def main():

    helptext = '''example:
    collab-reset-shared -a umcollab -p pass12word
    collab-reset-shared --a umcollab --password pass12word
    '''

    parser = argparse.ArgumentParser(
230
231
        description='Resets the password in Google and'
                    'kerberos for a shared account.',
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--account',
        '-a',
        help='The target account name.',
    )
    parser.add_argument(
        '--password',
        '-p',
        help='The new password to use.',
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use.',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    # Argument prompt fallback
    if not args.account:
        args.account = arg_prompt(
            'Target shared account to reset password for'
        )
        args.password = arg_prompt(
            '(optional) Password to set',
            default=''
        )

    # Argument sanity check
    _required = ['account']
    for r in _required:
        try:
            if isinstance(r, str):
                assert getattr(args, r)
            if isinstance(r, tuple):
                assert getattr(args, r[0]) or getattr(args, r[1])
        except AssertionError:
            print('Missing required argument {}'.format(r))

274
275
276
277
278
    # 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
279
    logger = logging.getLogger(__name__)
280
281
282
283
284
285
286
287
288
289
290
291
292
    logger.setLevel(logging.DEBUG)

    # 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()
293
294
295
296
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
297
298
299
    ch.setFormatter(formatter)
    logger.addHandler(ch)

300
301
302
303
    if not args.password:
        pool = string.ascii_letters + string.digits + '!@#$%&*'
        args.password = ''.join(choice(pool) for i in range(12))

304
    sa = SharedAccount(vars(args), config)
Rob Carleski's avatar
Rob Carleski committed
305
306
307
    sa.check_mcommunity()
    sa.check_box()
    sa.check_google()
308
309
310

    # Exit out if a shared account doesn't exist.
    if not sa.google_exists and not sa.box_exists:
Rob Carleski's avatar
Rob Carleski committed
311
        logger.error(
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
            'Entity does not exist as a shared account',
            extra={'entity': args.account}
        )
        exit(2)

    # Set the password in kerberos
    sa.set_kerberos_password()

    # Set in Google if available:
    if sa.google_exists:
        sa.set_google_password()

    # Upload password doc and share to group owners
    sa.upload_and_share_password()

    # Print canned text to send to the user.
    sa.print_canned_text()


if __name__ == '__main__':
    main()