source: fedd/federation/util.py @ 79b6596

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

Zero-length self-signed certs failed under python 2.4/M2Crypto0.13. This explicitly fixes them

  • Property mode set to 100644
File size: 5.1 KB
Line 
1#!/usr/local/bin/python
2
3import re
4import string
5import logging
6
7from M2Crypto import SSL
8from fedid import fedid
9
10
11# If this is an old enough version of M2Crypto.SSL that has an
12# ssl_verify_callback that doesn't allow 0-length signed certs, create a
13# version of that callback that does.  This is edited from the original in
14# M2Crypto.SSL.cb.  This version also elides the printing to stderr.
15if not getattr(SSL.cb, 'ssl_verify_callback_allow_unknown_ca', None):
16    from M2Crypto.SSL.Context import map
17    from M2Crypto import m2
18
19    def ssl_verify_callback(ssl_ctx_ptr, x509_ptr, errnum, errdepth, ok):
20        unknown_issuer = [
21            m2.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY,
22            m2.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE,
23            m2.X509_V_ERR_CERT_UNTRUSTED,
24            m2.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
25            ]
26        ssl_ctx = map()[ssl_ctx_ptr]
27
28        if errnum in unknown_issuer: 
29            if ssl_ctx.get_allow_unknown_ca():
30                ok = 1
31        # CRL checking goes here...
32        if ok:
33            if ssl_ctx.get_verify_depth() >= errdepth:
34                ok = 1
35            else:
36                ok = 0
37        return ok
38else:
39    def ssl_verify_callback(ssl_ctx_ptr, x509_ptr, errnum, errdepth, ok):
40        raise ValueError("This should never be called")
41
42class fedd_ssl_context(SSL.Context):
43    """
44    Simple wrapper around an M2Crypto.SSL.Context to initialize it for fedd.
45    """
46    def __init__(self, my_cert, trusted_certs=None, password=None):
47        """
48        construct a fedd_ssl_context
49
50        @param my_cert: PEM file with my certificate in it
51        @param trusted_certs: PEM file with trusted certs in it (optional)
52        """
53        SSL.Context.__init__(self)
54
55        # load_cert takes a callback to get a password, not a password, so if
56        # the caller provided a password, this creates a nonce callback using a
57        # lambda form.
58        if password != None and not callable(password):
59            # This is cute.  password = lambda *args: password produces a
60            # function object that returns itself rather than one that returns
61            # the object itself.  This is because password is an object
62            # reference and after the assignment it's a lambda.  So we assign
63            # to a temp.
64            pwd = password
65            password =lambda *args: pwd
66
67        if password != None:
68            self.load_cert(my_cert, callback=password)
69        else:
70            self.load_cert(my_cert)
71
72        # If no trusted certificates are specified, allow unknown CAs.
73        if trusted_certs: 
74            self.load_verify_locations(trusted_certs)
75            self.set_verify(SSL.verify_peer, 10)
76        else:
77            # More legacy code.  Recent versions of M2Crypto express the
78            # allow_unknown_ca option through a callback turned to allow it.
79            # Older versions use a standard callback that respects the
80            # attribute.  This should work under both regines.
81            callb = getattr(SSL.cb, 'ssl_verify_callback_allow_unknown_ca', 
82                    ssl_verify_callback)
83            self.set_allow_unknown_ca(True)
84            self.set_verify(SSL.verify_peer, 10, callback=callb)
85
86def read_simple_accessdb(fn, auth, mask=[]):
87    """
88    Read a simple access database.  Each line is a fedid (of the form
89    fedid:hexstring) and a comma separated list of atributes to be assigned to
90    it.  This parses out the fedids and adds the attributes to the authorizer.
91    comments (preceded with a #) and blank lines are ignored.  Exceptions (e.g.
92    file exceptions and ValueErrors from badly parsed lines) are propagated.
93    """
94
95    rv = [ ]
96    lineno = 0
97    fedid_line = re.compile("fedid:([" + string.hexdigits + "]+)\s+" +\
98            "(\w+\s*(,\s*\w+)*)")
99
100    # If a single string came in, make it a list
101    if isinstance(mask, basestring): mask = [ mask ]
102
103    f = open(fn, 'r')
104    for line in f:
105        lineno += 1
106        line = line.strip()
107        if line.startswith('#') or len(line) == 0: 
108            continue
109        m = fedid_line.match(line)
110        if m :
111            fid = fedid(hexstr=m.group(1))
112            for a in [ a.strip() for a in m.group(2).split(",") \
113                    if not mask or a.strip() in mask ]:
114                auth.set_attribute(fid, a.strip())
115        else:
116            raise ValueError("Badly formatted line in accessdb: %s line %d" %\
117                    (nf, lineno))
118    f.close()
119    return rv
120       
121
122def pack_id(id):
123    """
124    Return a dictionary with the field name set by the id type.  Handy for
125    creating dictionaries to be converted to messages.
126    """
127    if isinstance(id, fedid): return { 'fedid': id }
128    elif id.startswith("http:") or id.startswith("https:"): return { 'uri': id }
129    else: return { 'localname': id}
130
131def unpack_id(id):
132    """return id as a type determined by the key"""
133    for k in ("localname", "fedid", "uri", "kerberosUsername"):
134        if id.has_key(k): return id[k]
135    return None
136
137def set_log_level(config, sect, log):
138    """ Set the logging level to the value passed in sect of config."""
139    # The getattr sleight of hand finds the logging level constant
140    # corrersponding to the string.  We're a little paranoid to avoid user
141    # mayhem.
142    if config.has_option(sect, "log_level"):
143        level_str = config.get(sect, "log_level")
144        try:
145            level = int(getattr(logging, level_str.upper(), -1))
146
147            if  logging.DEBUG <= level <= logging.CRITICAL:
148                log.setLevel(level)
149            else:
150                log.error("Bad experiment_log value: %s" % level_str)
151
152        except ValueError:
153            log.error("Bad experiment_log value: %s" % level_str)
154
Note: See TracBrowser for help on using the repository browser.