source: fedd/federation/util.py @ 5d3f239

axis_examplecompt_changesinfo-opsversion-1.30version-2.00version-3.01version-3.02
Last change on this file since 5d3f239 was 5d3f239, checked in by Ted Faber <faber@…>, 15 years ago

change package name to avoid conflicts with fedd on install

  • Property mode set to 100644
File size: 3.7 KB
Line 
1#!/usr/local/bin/python
2
3import re
4import string
5import logging
6
7from M2Crypto import SSL
8from fedid import fedid
9
10class fedd_ssl_context(SSL.Context):
11    """
12    Simple wrapper around an M2Crypto.SSL.Context to initialize it for fedd.
13    """
14    def __init__(self, my_cert, trusted_certs=None, password=None):
15        """
16        construct a fedd_ssl_context
17
18        @param my_cert: PEM file with my certificate in it
19        @param trusted_certs: PEM file with trusted certs in it (optional)
20        """
21        SSL.Context.__init__(self)
22
23        # load_cert takes a callback to get a password, not a password, so if
24        # the caller provided a password, this creates a nonce callback using a
25        # lambda form.
26        if password != None and not callable(password):
27            # This is cute.  password = lambda *args: password produces a
28            # function object that returns itself rather than one that returns
29            # the object itself.  This is because password is an object
30            # reference and after the assignment it's a lambda.  So we assign
31            # to a temp.
32            pwd = password
33            password =lambda *args: pwd
34
35        if password != None:
36            self.load_cert(my_cert, callback=password)
37        else:
38            self.load_cert(my_cert)
39
40        # If no trusted certificates are specified, allow unknown CAs.
41        if trusted_certs: 
42            self.load_verify_locations(trusted_certs)
43            self.set_verify(SSL.verify_peer, 10)
44        else:
45            self.set_verify(SSL.verify_peer, 10, 
46                callback=SSL.cb.ssl_verify_callback_allow_unknown_ca)
47
48def read_simple_accessdb(fn, auth, mask=[]):
49    """
50    Read a simple access database.  Each line is a fedid (of the form
51    fedid:hexstring) and a comma separated list of atributes to be assigned to
52    it.  This parses out the fedids and adds the attributes to the authorizer.
53    comments (preceded with a #) and blank lines are ignored.  Exceptions (e.g.
54    file exceptions and ValueErrors from badly parsed lines) are propagated.
55    """
56
57    rv = [ ]
58    lineno = 0
59    fedid_line = re.compile("fedid:([" + string.hexdigits + "]+)\s+" +\
60            "(\w+\s*(,\s*\w+)*)")
61
62    # If a single string came in, make it a list
63    if isinstance(mask, basestring): mask = [ mask ]
64
65    f = open(fn, 'r')
66    for line in f:
67        lineno += 1
68        line = line.strip()
69        if line.startswith('#') or len(line) == 0: 
70            continue
71        m = fedid_line.match(line)
72        if m :
73            fid = fedid(hexstr=m.group(1))
74            for a in [ a.strip() for a in m.group(2).split(",") \
75                    if not mask or a.strip() in mask ]:
76                auth.set_attribute(fid, a.strip())
77        else:
78            raise ValueError("Badly formatted line in accessdb: %s line %d" %\
79                    (nf, lineno))
80    f.close()
81    return rv
82       
83
84def pack_id(id):
85    """
86    Return a dictionary with the field name set by the id type.  Handy for
87    creating dictionaries to be converted to messages.
88    """
89    if isinstance(id, fedid): return { 'fedid': id }
90    elif id.startswith("http:") or id.startswith("https:"): return { 'uri': id }
91    else: return { 'localname': id}
92
93def unpack_id(id):
94    """return id as a type determined by the key"""
95    for k in ("localname", "fedid", "uri", "kerberosUsername"):
96        if id.has_key(k): return id[k]
97    return None
98
99def set_log_level(config, sect, log):
100    """ Set the logging level to the value passed in sect of config."""
101    # The getattr sleight of hand finds the logging level constant
102    # corrersponding to the string.  We're a little paranoid to avoid user
103    # mayhem.
104    if config.has_option(sect, "log_level"):
105        level_str = config.get(sect, "log_level")
106        try:
107            level = int(getattr(logging, level_str.upper(), -1))
108
109            if  logging.DEBUG <= level <= logging.CRITICAL:
110                log.setLevel(level)
111            else:
112                log.error("Bad experiment_log value: %s" % level_str)
113
114        except ValueError:
115            log.error("Bad experiment_log value: %s" % level_str)
116
Note: See TracBrowser for help on using the repository browser.