source: fedd/access_to_abac.py @ bcc6fd6

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

Allow update of access controller policy

  • Property mode set to 100755
File size: 16.1 KB
RevLine 
[2e46f35]1#!/usr/bin/env python
[6cc5c81]2
3import sys, os
4import re
[87807f42]5import subprocess
[d894c21]6import os.path
[6cc5c81]7
[87807f42]8from string import join
[d894c21]9from optparse import OptionParser, OptionValueError
10from tempfile import mkdtemp
11
[cd360a0]12import Creddy
13
[6bedbdba]14from deter import fedid
[d894c21]15from federation.authorizer import abac_authorizer
[62f3dd9]16from federation.util import abac_split_cert, abac_pem_type, file_expanding_opts
[6cc5c81]17
[87807f42]18
[6cc5c81]19class attribute:
[af25848]20    '''
[87807f42]21    Encapculate a principal/attribute/link tuple.
[af25848]22    '''
[87807f42]23    bad_attr = re.compile('[^a-zA-Z0-9_]+')
24    def __init__(self, p, a, l=None):
[6cc5c81]25        self.principal = p
[87807f42]26        self.attr = attribute.bad_attr.sub('_', a)
27        if l: self.link = attribute.bad_attr.sub('_', l)
28        else: self.link = None
[6cc5c81]29
30    def __str__(self):
[87807f42]31        if self.link:
32            return "%s.%s.%s" % (self.principal, self.attr, self.link)
33        elif self.attr:
[af25848]34            return "%s.%s" % (self.principal, self.attr)
35        else:
36            return "%s" % self.principal
[6cc5c81]37
38class credential:
[af25848]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    '''
[87807f42]44    bad_attr = re.compile('[^a-zA-Z0-9_]+')
[6cc5c81]45    def __init__(self, p, a, req):
46        self.principal = p
47        if isinstance(a, (tuple, list, set)) and len(a) == 1:
[87807f42]48            self.attr = credential.bad_attr.sub('_', a[0])
[6cc5c81]49        else:
[87807f42]50            self.attr = credential.bad_attr.sub('_', a)
[6cc5c81]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, 
[87807f42]56                    join(["%s" % r for r in self.req], ' & '))
[6cc5c81]57        else:
58            return "%s.%s <- %s" % (self.principal, self.attr, self.req)
59
[353db8c]60# Mappinng generation function and the access parser throw these when there is
[af25848]61# a parsing problem.
[6cc5c81]62class parse_error(RuntimeError): pass
63
[87807f42]64# Error creating a credential
65class credential_error(RuntimeError): pass
66
[af25848]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
[f77a256]73#  add the new ABAC credential(s) that will be mapped into the local
[af25848]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.
[87807f42]77def parse_emulab(l, creds, me, to_id, p, gp, gu, lr):
[af25848]78    '''
[f77a256]79    Parse the emulab (project, allocation_user, cert_file) format.
[af25848]80    '''
[f77a256]81    right_side_str = '\s*,\s*\(\s*%s\s*,\s*%s\s*,\s*(%s)\s*\)' % \
82            (proj_same_str, id_same_str,path_str)
[6cc5c81]83
84    m = re.match(right_side_str, l)
85    if m:
[f77a256]86        project, user, cert = m.group(1,2,3)
[af25848]87        # Resolve "<same>"s in project and user
[6cc5c81]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:
[c324ad3]95                user = gu
[6cc5c81]96            else:
97                raise parse_error("User cannot be decisively mapped: %s" % l)
[af25848]98
99        # Create a semi-mnemonic name for the destination credential (the one
100        # that will be mapped to the local attributes
[c324ad3]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
[6cc5c81]107        else:
108            raise parse_error("No mapping for %s/%s!?" % (gp, gu))
109
[af25848]110        # Store the creds and map entries
[6cc5c81]111        c = credential(me, a, 
[87807f42]112                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
[6cc5c81]113        creds.add(c)
[f77a256]114        if (project, user,cert) in to_id: to_id[(project,user,cert)].append(c)
115        else: to_id[(project,user,cert)] = [ c ]
[6cc5c81]116    else:
117        raise parse_error("Badly formatted local mapping: %s" % l)
118
119
[87807f42]120def parse_protogeni(l, creds, me, to_id, p, gp, gu, lr):
[af25848]121    '''
122    Parse the protoGENI (cert, user, user_key, cert_pw) format.
123    '''
[5a721ed]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)
[af25848]130        # The credential is formed from just the path (with / mapped to _) and
131        # the username.
[5a721ed]132        acert = re.sub('/', '_', cert)
133
134        a = "cert_%s_user_%s" % (acert, user)
[af25848]135
136        # Store em
[5a721ed]137        c = credential(me, a, 
[87807f42]138                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
[5a721ed]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
[87807f42]147def parse_dragon(l, creds, me, to_id, p, gp, gu, lr):
[af25848]148    '''
149    Parse the dragon (repository_name) version.
150    '''
[6cc5c81]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, 
[87807f42]158                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
[6cc5c81]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)
[9cce15a]164
[87807f42]165def parse_skel(l, creds, me, to_id, p, gp, gu, lr):
[af25848]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, 
[87807f42]176                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
[af25848]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)
[9cce15a]182
[af25848]183# internal plug-ins have no local attributes.
[87807f42]184def parse_internal(l, creds, me, to_id, p, gp, gu, lr): pass
[6cc5c81]185
186
[3fa4328]187def parse_access(fn, mapper, delegation_link):
[d894c21]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
[62f3dd9]226class access_opts(file_expanding_opts):
[af25848]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
[9cce15a]232    mappers = { 
233            'emulab': parse_emulab, 
234            'dragon': parse_dragon,
235            'internal': parse_internal,
236            'skel': parse_skel,
[5a721ed]237            'protogeni': parse_protogeni,
[9cce15a]238            }
[6cc5c81]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' % \
[87807f42]246                    (s, join(access_opts.mappers.keys(), ', ')))
[6cc5c81]247
248    def __init__(self):
[62f3dd9]249        file_expanding_opts.__init__(self, usage='%prog [opts] file [...]')
[6cc5c81]250        self.add_option('--cert', dest='cert', default=None,
[62f3dd9]251                type='str', action='callback', callback=self.expand_file,
[6cc5c81]252                help='my fedid as an X.509 certificate')
253        self.add_option('--key', dest='key', default=None,
[62f3dd9]254                type='str', action='callback', callback=self.expand_file,
[6cc5c81]255                help='key for the certificate')
[5a721ed]256        self.add_option('--dir', dest='dir', default=None,
[62f3dd9]257                type='str', action='callback', callback=self.expand_file,
[5a721ed]258                help='Output directory for credentials')
[6cc5c81]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. ' %\
[87807f42]263                        join(access_opts.mappers.keys(), ', ') + \
[6cc5c81]264                        'Omit for generic parsing.')
[5a721ed]265        self.add_option('--quiet', dest='quiet', action='store_true', 
266                default=False,
267                help='Do not print credential to local attribute map')
[3fa4328]268        self.add_option('--no_create_creds', action='store_false', 
269                dest='create_creds', default=True,
270                help='Do not create credentials for rules.')
[87807f42]271        self.add_option('--file', dest='file', default=None,
[62f3dd9]272                type='str', action='callback', callback=self.expand_file,
[87807f42]273                help='Access DB to parse.  If this is present, ' + \
274                        'omit the positional filename')
275        self.add_option('--mapfile', dest='map', default=None,
[62f3dd9]276                type='str', action='callback', callback=self.expand_file,
[87807f42]277                help='File for the attribute to local authorization data')
[bfbaa85]278        self.add_option('--update', action='store_const', const=True,
279                dest='update_authorizer', default=False, 
280                help='Add the generated policy to an existing authorizer')
[87807f42]281        self.add_option('--no-delegate', action='store_false', dest='delegate',
282                default=True,
283                help='do not accept delegated attributes with the ' +\
284                        'acting_for linking role')
[5529264]285        self.add_option('--fed-root', dest='root', 
286                help='add a rule to accept federated users from facilities ' +\
287                        'recognized by ROOT.  This is a certificate file')
288        self.add_option('--fed-tuple', dest='ftuple', 
289                help='a tuple into which to map federated ' + \
290                        'users about which we know nothing else.')
[3fa4328]291        self.add_option('--no_auth', action='store_false', dest='create_auth', 
292                default=True, help='do not create a full ABAC authorizer')
[87807f42]293        self.add_option('--debug', action='store_true', dest='debug', 
294                default=False, help='Just print actions')
[6cc5c81]295        self.set_defaults(mapper=None)
296
[bfbaa85]297def create_creds(creds, cert, key, dir, debug=False):
[af25848]298    '''
[cd360a0]299    Make the the attributes from the list of credential
[af25848]300    objects in the creds parameter.
301    '''
[bfbaa85]302    cfiles = []
[5a721ed]303    for i, c in enumerate(creds):
[cd360a0]304        cid = Creddy.ID(cert)
305        cid.load_privkey(key)
306        cattr = Creddy.Attribute(cid, c.attr, 3600 * 24 * 365 * 10)
[5a721ed]307        for r in c.req:
[cd360a0]308            if r.principal and r.link and r.attr:
309                cattr.linking_role(r.principal, r.attr, r.link)
310            elif r.principal and r.attr:
311                cattr.role(r.principal, r.attr)
312            elif r.principal:
313                cattr.principal(r.principal)
314            else:
315                raise parse_error('Attribute without a principal?')
316        cattr.bake()
[bfbaa85]317        fn = '%s/cred%d_attr.der' % (dir, i)
318        cattr.write_name(fn)
319        cfiles.append(fn)
320    return cfiles
321
[6cc5c81]322
[d894c21]323def clear_dir(dir):
324    for path, dirs, files in os.walk(dir, topdown=False):
325        for f in files: os.unlink(os.path.join(path, f))
326        for d in dirs: os.rmdir(os.path.join(path, d))
327
[af25848]328# Regular expressions and parts thereof for parsing
[6cc5c81]329comment_re = re.compile('^\s*#|^$')
330fedid_str = 'fedid:([0-9a-fA-F]{40})'
[9cce15a]331id_str = '[a-zA-Z][\w_-]*'
[f3898f7]332proj_str = '[a-zA-Z][\w_/-]*'
[f77a256]333path_str = '[a-zA-Z0-9_/\.-]+'
[6cc5c81]334id_any_str = '(%s|<any>)' % id_str
[f3898f7]335proj_any_str = '(%s|<any>)' % proj_str
[6cc5c81]336id_same_str = '(%s|<same>)' % id_str
[f3898f7]337proj_same_str = '(%s|<same>)' % proj_str
[6cc5c81]338left_side_str = '\(\s*%s\s*,\s*%s\s*,\s*%s\s*\)' % \
[f3898f7]339        (fedid_str, proj_any_str, id_any_str)
[6cc5c81]340right_side_str = '(%s)(\s*,\s*\(.*\))?' % (id_str)
341line_re = re.compile('%s\s*->\s*%s' % (left_side_str, right_side_str))
342
343p = access_opts()
344opts, args = p.parse_args()
345
[de7cb08]346cert, key = None, None
347delete_certs = False
[d894c21]348delete_creds = False
[de7cb08]349
[87807f42]350if opts.file:
351    args.append(opts.file)
352
[af25848]353# Validate arguments
[6cc5c81]354if len(args) < 1:
355    sys.exit('No filenames given to parse')
356
[de7cb08]357if opts.key:
358    if not os.access(opts.key, os.R_OK):
359        key = opts.key
360    else:
361        sys.exit('Cannot read key (%s)' % opts.key)
[5a721ed]362
363if opts.dir:
[c324ad3]364    if not os.access(opts.dir, os.F_OK):
365        try:
366            os.mkdir(opts.dir, 0700)
367        except EnvironmentError, e:
368            sys.exit("Cannot create %s: %s" % (e.filename, e.strerror))
[5a721ed]369    if not os.path.isdir(opts.dir):
370        sys.exit('%s is not a directory' % opts.dir)
371    elif not os.access(opts.dir, os.W_OK):
372        sys.exit('%s is not writable' % opts.dir)
373
[d894c21]374if opts.create_auth:
375    creds_dir = mkdtemp()
376    delete_creds = True
377    auth_dir = opts.dir
[4909fcf]378    if not os.path.isabs(auth_dir):
379        sys.exit('Authorizer path must be absolute')
[d894c21]380else:
381    creds_dir = opts.dir
382    auth_dir = None
383
[87807f42]384if opts.delegate: delegation_link = 'acting_for'
385else: delegation_link = None
386
[a0e20ac]387if not opts.mapper and (opts.map or opts.debug):
388    print >>sys.stderr, "No --type specified, mapping file will be empty."
[6cc5c81]389
[de7cb08]390if opts.cert: 
[6cc5c81]391    try:
[de7cb08]392        me = fedid(file=opts.cert) 
[6cc5c81]393    except EnvironmentError, e:
[de7cb08]394        sys.exit('Bad --cert: %s (%s)' % (e.strerror, e.filename or '?!'))
[6cc5c81]395
[de7cb08]396    if not opts.key:
397        if abac_pem_type(opts.cert) == 'both':
398            key, cert = abac_split_cert(opts.cert)
399            delete_certs = True
400    else:
401        cert = opts.cert
402else: 
403    print >>sys.stderr, 'No --cert, using dummy fedid'
404    me = fedid(hexstr='0123456789012345678901234567890123456789')
405    cert = None
406
[5529264]407fed_to_id =  { }
408if any((opts.root, opts.ftuple)) and not all ((opts.root, opts.ftuple)):
409    sys.exit('Either both or neither of --fed-root and ' + \
410            '--fed-project must be specified')
411elif opts.root:
412    try:
413        root_fedid = fedid(file=opts.root)
414    except EnvironmentError, e:
415        sys.exit('Bad --root: %s (%s)' % (e.strerror, e.filename or '?!'))
416
417    fed_tuple = tuple(opts.ftuple.split(','))
418    fed_someuser_cred = \
419            credential(me, 'some_feduser', 
420                    [attribute(root_fedid.get_hexstr(), 
421                        'fedfacility', 'feduser')])
422    fed_user_cred = \
423            credential(me, 'default_feduser', 
424                    [attribute(me.get_hexstr(), 
425                        'some_feduser', 'acting_for')])
426    fed_access_cred = \
427            credential(me, 'access', 
428                    [attribute(me.get_hexstr(), 'default_feduser')])
429   
430    fed_to_id[fed_tuple] = [fed_user_cred]
431
432else:
433    # No fed-root or fed-tuple
434    fed_access_cred = None
435    fed_user_cred = None
436    fed_someuser_cred = None
[bfbaa85]437
438credfiles = []
[5529264]439   
[de7cb08]440# The try block makes sure that credentials split into tmp files are deleted
441try:
442    # Do the parsing
443    for fn in args:
[87807f42]444        try:
[3fa4328]445            creds, to_id = parse_access(fn, opts.mapper, delegation_link)
[de7cb08]446        except parse_error, e:
447            print >> sys.stderr, "%s" % e
448            continue
[87807f42]449        except EnvironmentError, e:
[de7cb08]450            print >>sys.stderr, "File error %s: %s" % \
451                    (e.filename or '!?', e.strerror) 
452            continue
453
454        # Credential output
455        if opts.create_creds:
[5529264]456            if fed_access_cred and fed_user_cred and fed_someuser_cred:
457                creds.add(fed_access_cred)
458                creds.add(fed_user_cred)
459                creds.add(fed_someuser_cred)
[de7cb08]460            if all([cert, key, opts.dir]):
461                try:
[bfbaa85]462                    credfiles = create_creds(
463                            [c for c in creds if c.principal == me],
[d894c21]464                            cert, key, creds_dir, opts.debug)
[de7cb08]465                except credential_error, e:
466                    sys.exit('Credential creation failed: %s' % e)
467            else:
[d894c21]468                print >>sys.stderr, 'Cannot create credentials.  ' + \
469                        'Missing parameter'
[de7cb08]470
471        # Local map output
472        if opts.map or opts.debug:
473            try:
474                if opts.map and opts.map != '-' and not opts.debug:
475                    f = open(opts.map, 'w')
476                else:
477                    f = sys.stdout
[5529264]478                for k, c in to_id.items() + fed_to_id.items():
[5d7f1e8]479                    # Keys are either a single string or a tuple of them; join
480                    # the tuples into a comma-separated string.
481                    if isinstance(k, basestring): rhs = k
482                    else: rhs = join(k, ', ')
483
[de7cb08]484                    for a in set(["%s.%s" % (x.principal, x.attr) for x in c]):
[5d7f1e8]485                        print >>f, "%s -> (%s)" % (a, rhs)
[de7cb08]486            except EnvironmentError, e:
[d894c21]487                sys.exit("Cannot open %s: %s" % (e.filename or '!?', 
488                    e.strerror))
489
490        # Create an authorizer if requested.
491        if opts.create_auth:
492            try:
493                # Pass in the options rather than the potentially split key
494                # because abac_authorizer will split it and store it
495                # internally.  The opts.cert may get split twice, but we won't
496                # lose one.
[bfbaa85]497                if opts.update_authorizer:
498                    operation = 'updat'
499                    a = abac_authorizer(load=auth_dir)
500                    a.import_credentials(file_list=credfiles)
501                    a.save()
502                else:
503                    clear_dir(auth_dir)
504                    operation = 'creat'
505                    a = abac_authorizer(key=opts.key, me=opts.cert, 
506                            certs=creds_dir, save=auth_dir)
507                    a.save(auth_dir)
[d894c21]508            except EnvironmentError, e:
[5d7f1e8]509                sys.exit("Can't create or write %s: %s" % \
510                        (e.filename, e.strerror))
[d894c21]511            except abac_authorizer.bad_cert_error, e:
[bfbaa85]512                sys.exit("Error %sing authorizer: %s" % (operation, e))
[d894c21]513
[de7cb08]514finally:
[d894c21]515    try:
516        if delete_certs:
517            if cert: os.unlink(cert)
518            if key: os.unlink(key)
519        if delete_creds and creds_dir:
520            clear_dir(creds_dir)
521            os.rmdir(creds_dir)
522    except EnvironmentError, e:
523        sys.exit("Can't remove %s: %s" % ( e.filename, e.strerror))
Note: See TracBrowser for help on using the repository browser.