#!/usr/local/bin/python import logging from M2Crypto import SSL from fedid import fedid class fedd_ssl_context(SSL.Context): """ Simple wrapper around an M2Crypto.SSL.Context to initialize it for fedd. """ def __init__(self, my_cert, trusted_certs=None, password=None): """ construct a fedd_ssl_context @param my_cert: PEM file with my certificate in it @param trusted_certs: PEM file with trusted certs in it (optional) """ SSL.Context.__init__(self) # load_cert takes a callback to get a password, not a password, so if # the caller provided a password, this creates a nonce callback using a # lambda form. if password != None and not callable(password): # This is cute. password = lambda *args: password produces a # function object that returns itself rather than one that returns # the object itself. This is because password is an object # reference and after the assignment it's a lambda. So we assign # to a temp. pwd = password password =lambda *args: pwd if password != None: self.load_cert(my_cert, callback=password) else: self.load_cert(my_cert) if trusted_certs != None: self.load_verify_locations(trusted_certs) self.set_verify(SSL.verify_peer, 10) def pack_id(id): """ Return a dictionary with the field name set by the id type. Handy for creating dictionaries to be converted to messages. """ if isinstance(id, fedid): return { 'fedid': id } elif id.startswith("http:") or id.startswith("https:"): return { 'uri': id } else: return { 'localname': id} def unpack_id(id): """return id as a type determined by the key""" for k in ("localname", "fedid", "uri", "kerberosUsername"): if id.has_key(k): return id[k] return None def set_log_level(config, sect, log): """ Set the logging level to the value passed in sect of config.""" # The getattr sleight of hand finds the logging level constant # corrersponding to the string. We're a little paranoid to avoid user # mayhem. if config.has_option(sect, "log_level"): level_str = config.get(sect, "log_level") try: level = int(getattr(logging, level_str.upper(), -1)) if logging.DEBUG <= level <= logging.CRITICAL: log.setLevel(level) else: log.error("Bad experiment_log value: %s" % level_str) except ValueError: log.error("Bad experiment_log value: %s" % level_str)