source: fedd/access_to_abac.py @ 5529264

compt_changes
Last change on this file since 5529264 was 5529264, checked in by Ted Faber <faber@…>, 12 years ago

Add commands for delegated federated users

  • Property mode set to 100755
File size: 15.6 KB
Line 
1#!/usr/bin/env python
2
3import sys, os
4import re
5import subprocess
6import os.path
7
8from string import join
9from optparse import OptionParser, OptionValueError
10from tempfile import mkdtemp
11
12import Creddy
13
14from deter import fedid
15from federation.authorizer import abac_authorizer
16from federation.util import abac_split_cert, abac_pem_type, file_expanding_opts
17
18
19class attribute:
20    '''
21    Encapculate a principal/attribute/link tuple.
22    '''
23    bad_attr = re.compile('[^a-zA-Z0-9_]+')
24    def __init__(self, p, a, l=None):
25        self.principal = p
26        self.attr = attribute.bad_attr.sub('_', a)
27        if l: self.link = attribute.bad_attr.sub('_', l)
28        else: self.link = None
29
30    def __str__(self):
31        if self.link:
32            return "%s.%s.%s" % (self.principal, self.attr, self.link)
33        elif self.attr:
34            return "%s.%s" % (self.principal, self.attr)
35        else:
36            return "%s" % self.principal
37
38class credential:
39    '''
40    A Credential, that is the requisites (as attributes) and the assigned
41    attribute (as principal, attr).   If req is iterable, the requirements are
42    an intersection/conjunction.
43    '''
44    bad_attr = re.compile('[^a-zA-Z0-9_]+')
45    def __init__(self, p, a, req):
46        self.principal = p
47        if isinstance(a, (tuple, list, set)) and len(a) == 1:
48            self.attr = credential.bad_attr.sub('_', a[0])
49        else:
50            self.attr = credential.bad_attr.sub('_', a)
51        self.req = req
52
53    def __str__(self):
54        if isinstance(self.req, (tuple, list, set)):
55            return "%s.%s <- %s" % (self.principal, self.attr, 
56                    join(["%s" % r for r in self.req], ' & '))
57        else:
58            return "%s.%s <- %s" % (self.principal, self.attr, self.req)
59
60# Mappinng generation function and the access parser throw these when there is
61# a parsing problem.
62class parse_error(RuntimeError): pass
63
64# Error creating a credential
65class credential_error(RuntimeError): pass
66
67# Functions to parse the individual access maps as well as an overall function
68# to parse generic ones.  The specific ones create a credential to local
69# attributes mapping and the global one creates the access policy credentials.
70
71#  All the local parsing functions get the unparsed remainder of the line
72#  (after the three-name and the attribute it maps to), the credential list to
73#  add the new ABAC credential(s) that will be mapped into the local
74#  credentials, the fedid of this entity, a dict mapping the local credentials
75#  to ABAC credentials that are required to exercise those local rights and the
76#  three-name (p, gp, gu) that is being mapped.
77def parse_emulab(l, creds, me, to_id, p, gp, gu, lr):
78    '''
79    Parse the emulab (project, allocation_user, cert_file) format.
80    '''
81    right_side_str = '\s*,\s*\(\s*%s\s*,\s*%s\s*,\s*(%s)\s*\)' % \
82            (proj_same_str, id_same_str,path_str)
83
84    m = re.match(right_side_str, l)
85    if m:
86        project, user, cert = m.group(1,2,3)
87        # Resolve "<same>"s in project and user
88        if project == '<same>':
89            if gp  is not None:
90                project = gp
91            else:
92                raise parse_error("Project cannot be decisively mapped: %s" % l)
93        if user == '<same>':
94            if gu is not None:
95                user = gu
96            else:
97                raise parse_error("User cannot be decisively mapped: %s" % l)
98
99        # Create a semi-mnemonic name for the destination credential (the one
100        # that will be mapped to the local attributes
101        if gp and gu:
102            a = 'project_%s_user_%s' % (gp, gu)
103        elif gp:
104            a = 'project_%s' % gp
105        elif gu:
106            a = 'user_%s' % gu
107        else:
108            raise parse_error("No mapping for %s/%s!?" % (gp, gu))
109
110        # Store the creds and map entries
111        c = credential(me, a, 
112                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
113        creds.add(c)
114        if (project, user,cert) in to_id: to_id[(project,user,cert)].append(c)
115        else: to_id[(project,user,cert)] = [ c ]
116    else:
117        raise parse_error("Badly formatted local mapping: %s" % l)
118
119
120def parse_protogeni(l, creds, me, to_id, p, gp, gu, lr):
121    '''
122    Parse the protoGENI (cert, user, user_key, cert_pw) format.
123    '''
124    right_side_str = '\s*,\s*\(\s*(%s)\s*,\s*(%s)\s*,\s*(%s)\s*,\s*(%s)\s*\)' \
125            % (path_str, id_str, path_str, id_str)
126
127    m = re.match(right_side_str, l)
128    if m:
129        cert, user, key, pw = m.group(1,2,3,4)
130        # The credential is formed from just the path (with / mapped to _) and
131        # the username.
132        acert = re.sub('/', '_', cert)
133
134        a = "cert_%s_user_%s" % (acert, user)
135
136        # Store em
137        c = credential(me, a, 
138                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
139        creds.add(c)
140        if (cert, user, key, pw) in to_id: 
141            to_id[(cert, user, key, pw)].append(c)
142        else: 
143            to_id[(cert, user, key, pw)] = [ c ]
144    else:
145        raise parse_error("Badly formatted local mapping: %s" % l)
146
147def parse_dragon(l, creds, me, to_id, p, gp, gu, lr):
148    '''
149    Parse the dragon (repository_name) version.
150    '''
151    right_side_str = '\s*,\s*\(\s*(%s)\s*\)' % \
152            (id_str)
153
154    m = re.match(right_side_str, l)
155    if m:
156        repo= m.group(1)
157        c = credential(me, 'repo_%s' % repo, 
158                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
159        creds.add(c)
160        if repo in to_id: to_id[repo].append(c)
161        else: to_id[repo] = [ c ]
162    else:
163        raise parse_error("Badly formatted local mapping: %s" % l)
164
165def parse_skel(l, creds, me, to_id, p, gp, gu, lr):
166    '''
167    Parse the skeleton (local_attr) version.
168    '''
169    right_side_str = '\s*,\s*\(\s*(%s)\s*\)' % \
170            (id_str)
171
172    m = re.match(right_side_str, l)
173    if m:
174        lattr = m.group(1)
175        c = credential(me, 'lattr_%s' % lattr, 
176                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
177        creds.add(c)
178        if lattr in to_id: to_id[lattr].append(c)
179        else: to_id[lattr] = [ c ]
180    else:
181        raise parse_error("Badly formatted local mapping: %s" % l)
182
183# internal plug-ins have no local attributes.
184def parse_internal(l, creds, me, to_id, p, gp, gu, lr): pass
185
186
187def parse_access(fn, mapper, delegation_link):
188    """
189    Parse the access file, calling out to the mapper to parse specific
190    credential types.  Mappers are above this code.
191    """
192    creds = set()
193    to_id = { }
194    f = open(fn, "r")
195    for i, l in enumerate(f):
196        try:
197            if comment_re.match(l):
198                continue
199            else:
200                m =  line_re.match(l)
201                if m:
202                    p, da = m.group(1, 4)
203                    gp, gu = m.group(2, 3)
204                    if gp == '<any>': gp = None
205                    if gu == '<any>': gu = None
206
207                    creds.add(credential(me, da, 
208                            [attribute(p, x, delegation_link) \
209                                    for x in (gp, gu) \
210                                        if x is not None]))
211                    if m.group(5) and mapper:
212                        mapper(m.group(5), creds, me, to_id, p, gp, gu,
213                                delegation_link)
214                else:
215                    raise parse_error('Syntax error')
216        except parse_error, e:
217            f.close()
218            raise parse_error('Error on line %d of %s: %s' % \
219                    (i, fn, e.message))
220    f.close()
221
222    return creds, to_id
223
224
225
226class access_opts(file_expanding_opts):
227    '''
228    Parse the options for this program.  Most are straightforward, but the
229    mapper uses a callback to convert from a string to a local mapper function.
230    '''
231    # Valid mappers
232    mappers = { 
233            'emulab': parse_emulab, 
234            'dragon': parse_dragon,
235            'internal': parse_internal,
236            'skel': parse_skel,
237            'protogeni': parse_protogeni,
238            }
239
240    @staticmethod
241    def parse_mapper(opt, s, val, parser, dest):
242        if val in access_opts.mappers:
243            setattr(parser.values, dest, access_opts.mappers[val])
244        else:
245            raise OptionValueError('%s must be one of %s' % \
246                    (s, join(access_opts.mappers.keys(), ', ')))
247
248    def __init__(self):
249        file_expanding_opts.__init__(self, usage='%prog [opts] file [...]')
250        self.add_option('--cert', dest='cert', default=None,
251                type='str', action='callback', callback=self.expand_file,
252                help='my fedid as an X.509 certificate')
253        self.add_option('--key', dest='key', default=None,
254                type='str', action='callback', callback=self.expand_file,
255                help='key for the certificate')
256        self.add_option('--dir', dest='dir', default=None,
257                type='str', action='callback', callback=self.expand_file,
258                help='Output directory for credentials')
259        self.add_option('--type', action='callback', nargs=1, type='str',
260                callback=access_opts.parse_mapper, 
261                callback_kwargs = { 'dest': 'mapper'}, 
262                help='Type of access file to parse.  One of %s. ' %\
263                        join(access_opts.mappers.keys(), ', ') + \
264                        'Omit for generic parsing.')
265        self.add_option('--quiet', dest='quiet', action='store_true', 
266                default=False,
267                help='Do not print credential to local attribute map')
268        self.add_option('--no_create_creds', action='store_false', 
269                dest='create_creds', default=True,
270                help='Do not create credentials for rules.')
271        self.add_option('--file', dest='file', default=None,
272                type='str', action='callback', callback=self.expand_file,
273                help='Access DB to parse.  If this is present, ' + \
274                        'omit the positional filename')
275        self.add_option('--mapfile', dest='map', default=None,
276                type='str', action='callback', callback=self.expand_file,
277                help='File for the attribute to local authorization data')
278        self.add_option('--no-delegate', action='store_false', dest='delegate',
279                default=True,
280                help='do not accept delegated attributes with the ' +\
281                        'acting_for linking role')
282        self.add_option('--fed-root', dest='root', 
283                help='add a rule to accept federated users from facilities ' +\
284                        'recognized by ROOT.  This is a certificate file')
285        self.add_option('--fed-tuple', dest='ftuple', 
286                help='a tuple into which to map federated ' + \
287                        'users about which we know nothing else.')
288        self.add_option('--no_auth', action='store_false', dest='create_auth', 
289                default=True, help='do not create a full ABAC authorizer')
290        self.add_option('--debug', action='store_true', dest='debug', 
291                default=False, help='Just print actions')
292        self.set_defaults(mapper=None)
293
294def create_creds(creds, cert, key, dir, debug=False, 
295        creddy='/usr/local/bin/creddy'):
296    '''
297    Make the the attributes from the list of credential
298    objects in the creds parameter.
299    '''
300    for i, c in enumerate(creds):
301        cid = Creddy.ID(cert)
302        cid.load_privkey(key)
303        cattr = Creddy.Attribute(cid, c.attr, 3600 * 24 * 365 * 10)
304        for r in c.req:
305            if r.principal and r.link and r.attr:
306                cattr.linking_role(r.principal, r.attr, r.link)
307            elif r.principal and r.attr:
308                cattr.role(r.principal, r.attr)
309            elif r.principal:
310                cattr.principal(r.principal)
311            else:
312                raise parse_error('Attribute without a principal?')
313        cattr.bake()
314        cattr.write_name('%s/cred%d_attr.der' % (dir, i))
315
316def clear_dir(dir):
317    for path, dirs, files in os.walk(dir, topdown=False):
318        for f in files: os.unlink(os.path.join(path, f))
319        for d in dirs: os.rmdir(os.path.join(path, d))
320
321# Regular expressions and parts thereof for parsing
322comment_re = re.compile('^\s*#|^$')
323fedid_str = 'fedid:([0-9a-fA-F]{40})'
324id_str = '[a-zA-Z][\w_-]*'
325proj_str = '[a-zA-Z][\w_/-]*'
326path_str = '[a-zA-Z0-9_/\.-]+'
327id_any_str = '(%s|<any>)' % id_str
328proj_any_str = '(%s|<any>)' % proj_str
329id_same_str = '(%s|<same>)' % id_str
330proj_same_str = '(%s|<same>)' % proj_str
331left_side_str = '\(\s*%s\s*,\s*%s\s*,\s*%s\s*\)' % \
332        (fedid_str, proj_any_str, id_any_str)
333right_side_str = '(%s)(\s*,\s*\(.*\))?' % (id_str)
334line_re = re.compile('%s\s*->\s*%s' % (left_side_str, right_side_str))
335
336p = access_opts()
337opts, args = p.parse_args()
338
339cert, key = None, None
340delete_certs = False
341delete_creds = False
342
343if opts.file:
344    args.append(opts.file)
345
346# Validate arguments
347if len(args) < 1:
348    sys.exit('No filenames given to parse')
349
350if opts.key:
351    if not os.access(opts.key, os.R_OK):
352        key = opts.key
353    else:
354        sys.exit('Cannot read key (%s)' % opts.key)
355
356if opts.dir:
357    if not os.access(opts.dir, os.F_OK):
358        try:
359            os.mkdir(opts.dir, 0700)
360        except EnvironmentError, e:
361            sys.exit("Cannot create %s: %s" % (e.filename, e.strerror))
362    if not os.path.isdir(opts.dir):
363        sys.exit('%s is not a directory' % opts.dir)
364    elif not os.access(opts.dir, os.W_OK):
365        sys.exit('%s is not writable' % opts.dir)
366
367if opts.create_auth:
368    creds_dir = mkdtemp()
369    delete_creds = True
370    auth_dir = opts.dir
371    if not os.path.isabs(auth_dir):
372        sys.exit('Authorizer path must be absolute')
373else:
374    creds_dir = opts.dir
375    auth_dir = None
376
377if opts.delegate: delegation_link = 'acting_for'
378else: delegation_link = None
379
380if not opts.mapper and (opts.map or opts.debug):
381    print >>sys.stderr, "No --type specified, mapping file will be empty."
382
383if opts.cert: 
384    try:
385        me = fedid(file=opts.cert) 
386    except EnvironmentError, e:
387        sys.exit('Bad --cert: %s (%s)' % (e.strerror, e.filename or '?!'))
388
389    if not opts.key:
390        if abac_pem_type(opts.cert) == 'both':
391            key, cert = abac_split_cert(opts.cert)
392            delete_certs = True
393    else:
394        cert = opts.cert
395else: 
396    print >>sys.stderr, 'No --cert, using dummy fedid'
397    me = fedid(hexstr='0123456789012345678901234567890123456789')
398    cert = None
399
400fed_to_id =  { }
401if any((opts.root, opts.ftuple)) and not all ((opts.root, opts.ftuple)):
402    sys.exit('Either both or neither of --fed-root and ' + \
403            '--fed-project must be specified')
404elif opts.root:
405    try:
406        root_fedid = fedid(file=opts.root)
407    except EnvironmentError, e:
408        sys.exit('Bad --root: %s (%s)' % (e.strerror, e.filename or '?!'))
409
410    fed_tuple = tuple(opts.ftuple.split(','))
411    fed_someuser_cred = \
412            credential(me, 'some_feduser', 
413                    [attribute(root_fedid.get_hexstr(), 
414                        'fedfacility', 'feduser')])
415    fed_user_cred = \
416            credential(me, 'default_feduser', 
417                    [attribute(me.get_hexstr(), 
418                        'some_feduser', 'acting_for')])
419    fed_access_cred = \
420            credential(me, 'access', 
421                    [attribute(me.get_hexstr(), 'default_feduser')])
422   
423    fed_to_id[fed_tuple] = [fed_user_cred]
424
425else:
426    # No fed-root or fed-tuple
427    fed_access_cred = None
428    fed_user_cred = None
429    fed_someuser_cred = None
430   
431# The try block makes sure that credentials split into tmp files are deleted
432try:
433    # Do the parsing
434    for fn in args:
435        try:
436            creds, to_id = parse_access(fn, opts.mapper, delegation_link)
437        except parse_error, e:
438            print >> sys.stderr, "%s" % e
439            continue
440        except EnvironmentError, e:
441            print >>sys.stderr, "File error %s: %s" % \
442                    (e.filename or '!?', e.strerror) 
443            continue
444
445        # Credential output
446        if opts.create_creds:
447            if fed_access_cred and fed_user_cred and fed_someuser_cred:
448                creds.add(fed_access_cred)
449                creds.add(fed_user_cred)
450                creds.add(fed_someuser_cred)
451            if all([cert, key, opts.dir]):
452                try:
453                    create_creds([c for c in creds if c.principal == me],
454                            cert, key, creds_dir, opts.debug)
455                except credential_error, e:
456                    sys.exit('Credential creation failed: %s' % e)
457            else:
458                print >>sys.stderr, 'Cannot create credentials.  ' + \
459                        'Missing parameter'
460
461        # Local map output
462        if opts.map or opts.debug:
463            try:
464                if opts.map and opts.map != '-' and not opts.debug:
465                    f = open(opts.map, 'w')
466                else:
467                    f = sys.stdout
468                for k, c in to_id.items() + fed_to_id.items():
469                    # Keys are either a single string or a tuple of them; join
470                    # the tuples into a comma-separated string.
471                    if isinstance(k, basestring): rhs = k
472                    else: rhs = join(k, ', ')
473
474                    for a in set(["%s.%s" % (x.principal, x.attr) for x in c]):
475                        print >>f, "%s -> (%s)" % (a, rhs)
476            except EnvironmentError, e:
477                sys.exit("Cannot open %s: %s" % (e.filename or '!?', 
478                    e.strerror))
479
480        # Create an authorizer if requested.
481        if opts.create_auth:
482            clear_dir(auth_dir)
483            try:
484                # Pass in the options rather than the potentially split key
485                # because abac_authorizer will split it and store it
486                # internally.  The opts.cert may get split twice, but we won't
487                # lose one.
488                a = abac_authorizer(key=opts.key, me=opts.cert, 
489                        certs=creds_dir, save=auth_dir)
490                a.save(auth_dir)
491            except EnvironmentError, e:
492                sys.exit("Can't create or write %s: %s" % \
493                        (e.filename, e.strerror))
494            except abac_authorizer.bad_cert_error, e:
495                sys.exit("Error creating authorizer: %s" % e)
496
497finally:
498    try:
499        if delete_certs:
500            if cert: os.unlink(cert)
501            if key: os.unlink(key)
502        if delete_creds and creds_dir:
503            clear_dir(creds_dir)
504            os.rmdir(creds_dir)
505    except EnvironmentError, e:
506        sys.exit("Can't remove %s: %s" % ( e.filename, e.strerror))
Note: See TracBrowser for help on using the repository browser.