source: fedd/access_to_abac.py @ 4909fcf

compt_changesinfo-ops
Last change on this file since 4909fcf was 4909fcf, checked in by Ted Faber <faber@…>, 13 years ago

Force authorizer paths to be absolute

  • Property mode set to 100755
File size: 14.2 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 federation.fedid 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 loacl
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, access_user) format.  Access
80    users are deprecates and allocation users used for both.  This fuction
81    collapses them.
82    '''
83    right_side_str = '\s*,\s*\(\s*%s\s*,\s*%s\s*,\s*%s\s*\)' % \
84            (id_same_str, id_same_str,id_same_str)
85
86    m = re.match(right_side_str, l)
87    if m:
88        project, user = m.group(1,2)
89        # Resolve "<same>"s in project and user
90        if project == '<same>':
91            if gp  is not None:
92                project = gp
93            else:
94                raise parse_error("Project cannot be decisively mapped: %s" % l)
95        if user == '<same>':
96            if gu is not None:
97                user = gu
98            else:
99                raise parse_error("User cannot be decisively mapped: %s" % l)
100
101        # Create a semi-mnemonic name for the destination credential (the one
102        # that will be mapped to the local attributes
103        if gp and gu:
104            a = 'project_%s_user_%s' % (gp, gu)
105        elif gp:
106            a = 'project_%s' % gp
107        elif gu:
108            a = 'user_%s' % gu
109        else:
110            raise parse_error("No mapping for %s/%s!?" % (gp, gu))
111
112        # Store the creds and map entries
113        c = credential(me, a, 
114                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
115        creds.add(c)
116        if (project, user) in to_id: to_id[(project,user)].append(c)
117        else: to_id[(project,user)] = [ c ]
118    else:
119        raise parse_error("Badly formatted local mapping: %s" % l)
120
121
122def parse_protogeni(l, creds, me, to_id, p, gp, gu, lr):
123    '''
124    Parse the protoGENI (cert, user, user_key, cert_pw) format.
125    '''
126    right_side_str = '\s*,\s*\(\s*(%s)\s*,\s*(%s)\s*,\s*(%s)\s*,\s*(%s)\s*\)' \
127            % (path_str, id_str, path_str, id_str)
128
129    m = re.match(right_side_str, l)
130    if m:
131        cert, user, key, pw = m.group(1,2,3,4)
132        # The credential is formed from just the path (with / mapped to _) and
133        # the username.
134        acert = re.sub('/', '_', cert)
135
136        a = "cert_%s_user_%s" % (acert, user)
137
138        # Store em
139        c = credential(me, a, 
140                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
141        creds.add(c)
142        if (cert, user, key, pw) in to_id: 
143            to_id[(cert, user, key, pw)].append(c)
144        else: 
145            to_id[(cert, user, key, pw)] = [ c ]
146    else:
147        raise parse_error("Badly formatted local mapping: %s" % l)
148
149def parse_dragon(l, creds, me, to_id, p, gp, gu, lr):
150    '''
151    Parse the dragon (repository_name) version.
152    '''
153    right_side_str = '\s*,\s*\(\s*(%s)\s*\)' % \
154            (id_str)
155
156    m = re.match(right_side_str, l)
157    if m:
158        repo= m.group(1)
159        c = credential(me, 'repo_%s' % repo, 
160                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
161        creds.add(c)
162        if repo in to_id: to_id[repo].append(c)
163        else: to_id[repo] = [ c ]
164    else:
165        raise parse_error("Badly formatted local mapping: %s" % l)
166
167def parse_skel(l, creds, me, to_id, p, gp, gu, lr):
168    '''
169    Parse the skeleton (local_attr) version.
170    '''
171    right_side_str = '\s*,\s*\(\s*(%s)\s*\)' % \
172            (id_str)
173
174    m = re.match(right_side_str, l)
175    if m:
176        lattr = m.group(1)
177        c = credential(me, 'lattr_%s' % lattr, 
178                [attribute(p, x, lr) for x in (gp, gu) if x is not None])
179        creds.add(c)
180        if lattr in to_id: to_id[lattr].append(c)
181        else: to_id[lattr] = [ c ]
182    else:
183        raise parse_error("Badly formatted local mapping: %s" % l)
184
185# internal plug-ins have no local attributes.
186def parse_internal(l, creds, me, to_id, p, gp, gu, lr): pass
187
188
189def parse_access(fn, mapper, delegation_link):
190    """
191    Parse the access file, calling out to the mapper to parse specific
192    credential types.  Mappers are above this code.
193    """
194    creds = set()
195    to_id = { }
196    f = open(fn, "r")
197    for i, l in enumerate(f):
198        try:
199            if comment_re.match(l):
200                continue
201            else:
202                m =  line_re.match(l)
203                if m:
204                    p, da = m.group(1, 4)
205                    gp, gu = m.group(2, 3)
206                    if gp == '<any>': gp = None
207                    if gu == '<any>': gu = None
208
209                    creds.add(credential(me, da, 
210                            [attribute(p, x, delegation_link) \
211                                    for x in (gp, gu) \
212                                        if x is not None]))
213                    if m.group(5) and mapper:
214                        mapper(m.group(5), creds, me, to_id, p, gp, gu,
215                                delegation_link)
216                else:
217                    raise parse_error('Syntax error')
218        except parse_error, e:
219            f.close()
220            raise parse_error('Error on line %d of %s: %s' % \
221                    (i, fn, e.message))
222    f.close()
223
224    return creds, to_id
225
226
227
228class access_opts(file_expanding_opts):
229    '''
230    Parse the options for this program.  Most are straightforward, but the
231    mapper uses a callback to convert from a string to a local mapper function.
232    '''
233    # Valid mappers
234    mappers = { 
235            'emulab': parse_emulab, 
236            'dragon': parse_dragon,
237            'internal': parse_internal,
238            'skel': parse_skel,
239            'protogeni': parse_protogeni,
240            }
241
242    @staticmethod
243    def parse_mapper(opt, s, val, parser, dest):
244        if val in access_opts.mappers:
245            setattr(parser.values, dest, access_opts.mappers[val])
246        else:
247            raise OptionValueError('%s must be one of %s' % \
248                    (s, join(access_opts.mappers.keys(), ', ')))
249
250    def __init__(self):
251        file_expanding_opts.__init__(self, usage='%prog [opts] file [...]')
252        self.add_option('--cert', dest='cert', default=None,
253                type='str', action='callback', callback=self.expand_file,
254                help='my fedid as an X.509 certificate')
255        self.add_option('--key', dest='key', default=None,
256                type='str', action='callback', callback=self.expand_file,
257                help='key for the certificate')
258        self.add_option('--dir', dest='dir', default=None,
259                type='str', action='callback', callback=self.expand_file,
260                help='Output directory for credentials')
261        self.add_option('--type', action='callback', nargs=1, type='str',
262                callback=access_opts.parse_mapper, 
263                callback_kwargs = { 'dest': 'mapper'}, 
264                help='Type of access file to parse.  One of %s. ' %\
265                        join(access_opts.mappers.keys(), ', ') + \
266                        'Omit for generic parsing.')
267        self.add_option('--quiet', dest='quiet', action='store_true', 
268                default=False,
269                help='Do not print credential to local attribute map')
270        self.add_option('--no_create_creds', action='store_false', 
271                dest='create_creds', default=True,
272                help='Do not create credentials for rules.')
273        self.add_option('--file', dest='file', default=None,
274                type='str', action='callback', callback=self.expand_file,
275                help='Access DB to parse.  If this is present, ' + \
276                        'omit the positional filename')
277        self.add_option('--mapfile', dest='map', default=None,
278                type='str', action='callback', callback=self.expand_file,
279                help='File for the attribute to local authorization data')
280        self.add_option('--no-delegate', action='store_false', dest='delegate',
281                default=True,
282                help='do not accept delegated attributes with the ' +\
283                        'acting_for linking role')
284        self.add_option('--no_auth', action='store_false', dest='create_auth', 
285                default=True, help='do not create a full ABAC authorizer')
286        self.add_option('--debug', action='store_true', dest='debug', 
287                default=False, help='Just print actions')
288        self.set_defaults(mapper=None)
289
290def create_creds(creds, cert, key, dir, debug=False, 
291        creddy='/usr/local/bin/creddy'):
292    '''
293    Make the the attributes from the list of credential
294    objects in the creds parameter.
295    '''
296    for i, c in enumerate(creds):
297        cid = Creddy.ID(cert)
298        cid.load_privkey(key)
299        cattr = Creddy.Attribute(cid, c.attr, 3600 * 24 * 365 * 10)
300        for r in c.req:
301            if r.principal and r.link and r.attr:
302                cattr.linking_role(r.principal, r.attr, r.link)
303            elif r.principal and r.attr:
304                cattr.role(r.principal, r.attr)
305            elif r.principal:
306                cattr.principal(r.principal)
307            else:
308                raise parse_error('Attribute without a principal?')
309        cattr.bake()
310        cattr.write_name('%s/cred%d_attr.der' % (dir, i))
311
312def clear_dir(dir):
313    for path, dirs, files in os.walk(dir, topdown=False):
314        for f in files: os.unlink(os.path.join(path, f))
315        for d in dirs: os.rmdir(os.path.join(path, d))
316
317# Regular expressions and parts thereof for parsing
318comment_re = re.compile('^\s*#|^$')
319fedid_str = 'fedid:([0-9a-fA-F]{40})'
320id_str = '[a-zA-Z][\w_-]*'
321path_str = '[a-zA-Z_/\.-]+'
322id_any_str = '(%s|<any>)' % id_str
323id_same_str = '(%s|<same>)' % id_str
324left_side_str = '\(\s*%s\s*,\s*%s\s*,\s*%s\s*\)' % \
325        (fedid_str, id_any_str, id_any_str)
326right_side_str = '(%s)(\s*,\s*\(.*\))?' % (id_str)
327line_re = re.compile('%s\s*->\s*%s' % (left_side_str, right_side_str))
328
329p = access_opts()
330opts, args = p.parse_args()
331
332cert, key = None, None
333delete_certs = False
334delete_creds = False
335
336if opts.file:
337    args.append(opts.file)
338
339# Validate arguments
340if len(args) < 1:
341    sys.exit('No filenames given to parse')
342
343if opts.key:
344    if not os.access(opts.key, os.R_OK):
345        key = opts.key
346    else:
347        sys.exit('Cannot read key (%s)' % opts.key)
348
349if opts.dir:
350    if not os.access(opts.dir, os.F_OK):
351        try:
352            os.mkdir(opts.dir, 0700)
353        except EnvironmentError, e:
354            sys.exit("Cannot create %s: %s" % (e.filename, e.strerror))
355    if not os.path.isdir(opts.dir):
356        sys.exit('%s is not a directory' % opts.dir)
357    elif not os.access(opts.dir, os.W_OK):
358        sys.exit('%s is not writable' % opts.dir)
359
360if opts.create_auth:
361    creds_dir = mkdtemp()
362    delete_creds = True
363    auth_dir = opts.dir
364    if not os.path.isabs(auth_dir):
365        sys.exit('Authorizer path must be absolute')
366else:
367    creds_dir = opts.dir
368    auth_dir = None
369
370if opts.delegate: delegation_link = 'acting_for'
371else: delegation_link = None
372
373if not opts.mapper and (opts.map or opts.debug):
374    print >>sys.stderr, "No --type specified, mapping file will be empty."
375
376if opts.cert: 
377    try:
378        me = fedid(file=opts.cert) 
379    except EnvironmentError, e:
380        sys.exit('Bad --cert: %s (%s)' % (e.strerror, e.filename or '?!'))
381
382    if not opts.key:
383        if abac_pem_type(opts.cert) == 'both':
384            key, cert = abac_split_cert(opts.cert)
385            delete_certs = True
386    else:
387        cert = opts.cert
388else: 
389    print >>sys.stderr, 'No --cert, using dummy fedid'
390    me = fedid(hexstr='0123456789012345678901234567890123456789')
391    cert = None
392
393# The try block makes sure that credentials split into tmp files are deleted
394try:
395    # Do the parsing
396    for fn in args:
397        try:
398            creds, to_id = parse_access(fn, opts.mapper, delegation_link)
399        except parse_error, e:
400            print >> sys.stderr, "%s" % e
401            continue
402
403        except EnvironmentError, e:
404            print >>sys.stderr, "File error %s: %s" % \
405                    (e.filename or '!?', e.strerror) 
406            continue
407
408        # Credential output
409        if opts.create_creds:
410            if all([cert, key, opts.dir]):
411                try:
412                    create_creds([c for c in creds if c.principal == me],
413                            cert, key, creds_dir, opts.debug)
414                except credential_error, e:
415                    sys.exit('Credential creation failed: %s' % e)
416            else:
417                print >>sys.stderr, 'Cannot create credentials.  ' + \
418                        'Missing parameter'
419
420        # Local map output
421        if opts.map or opts.debug:
422            try:
423                if opts.map and opts.map != '-' and not opts.debug:
424                    f = open(opts.map, 'w')
425                else:
426                    f = sys.stdout
427                for k, c in to_id.items():
428                    # Keys are either a single string or a tuple of them; join
429                    # the tuples into a comma-separated string.
430                    if isinstance(k, basestring): rhs = k
431                    else: rhs = join(k, ', ')
432
433                    for a in set(["%s.%s" % (x.principal, x.attr) for x in c]):
434                        print >>f, "%s -> (%s)" % (a, rhs)
435            except EnvironmentError, e:
436                sys.exit("Cannot open %s: %s" % (e.filename or '!?', 
437                    e.strerror))
438
439        # Create an authorizer if requested.
440        if opts.create_auth:
441            clear_dir(auth_dir)
442            try:
443                # Pass in the options rather than the potentially split key
444                # because abac_authorizer will split it and store it
445                # internally.  The opts.cert may get split twice, but we won't
446                # lose one.
447                a = abac_authorizer(key=opts.key, me=opts.cert, 
448                        certs=creds_dir, save=auth_dir)
449                a.save(auth_dir)
450            except EnvironmentError, e:
451                sys.exit("Can't create or write %s: %s" % \
452                        (e.filename, e.strerror))
453            except abac_authorizer.bad_cert_error, e:
454                sys.exit("Error creating authorizer: %s" % e)
455
456finally:
457    try:
458        if delete_certs:
459            if cert: os.unlink(cert)
460            if key: os.unlink(key)
461        if delete_creds and creds_dir:
462            clear_dir(creds_dir)
463            os.rmdir(creds_dir)
464    except EnvironmentError, e:
465        sys.exit("Can't remove %s: %s" % ( e.filename, e.strerror))
Note: See TracBrowser for help on using the repository browser.