コード例 #1
0
    def testCCacheFileBadFormat(self):
        os.system('echo > %s' % config.user_ccache_file)
        context = krbV.default_context()
        ccache = krbV.CCache(config.user_ccache_file, context=context)
        principal = krbV.Principal(config.service_principal, context=context)
        result = is_initialize_ccache_necessary(context, ccache, principal)
        self.assert_(result)

        if config.run_under_user_principal:
            context = krbV.default_context()
            ccache = krbV.CCache(config.user_ccache_file, context=context)
            principal = krbV.Principal(config.user_principal, context=context)
            result = is_initialize_ccache_necessary(context, ccache, principal)
            self.assert_(result)
コード例 #2
0
    def testCCacheFileNotFound(self):
        os.system('kdestroy -c %s 2>/dev/null' % config.user_ccache_file)
        context = krbV.default_context()
        ccache = krbV.CCache(config.user_ccache_file, context=context)
        principal = krbV.Principal(config.service_principal, context=context)
        result = is_initialize_ccache_necessary(context, ccache, principal)
        self.assert_(result)

        if config.run_under_user_principal:
            context = krbV.default_context()
            ccache = krbV.CCache(config.user_ccache_file, context=context)
            principal = krbV.Principal(config.user_principal, context=context)
            result = is_initialize_ccache_necessary(context, ccache, principal)
            self.assert_(result)
コード例 #3
0
    def testInitCCacheIsUnnecessary(self):
        if config.run_under_user_principal:
            init_user_ccache()
            context = krbV.default_context()
            ccache = krbV.CCache(config.user_ccache_file, context=context)
            principal = krbV.Principal(config.user_principal, context=context)
            result = is_initialize_ccache_necessary(context, ccache, principal)
            self.assertFalse(result)

        init_ccache_using_keytab()
        context = krbV.default_context()
        ccache = krbV.CCache(config.user_ccache_file, context=context)
        principal = krbV.Principal(config.service_principal, context=context)
        result = is_initialize_ccache_necessary(context, ccache, principal)
        self.assertFalse(result)
コード例 #4
0
def tcp_client(opts, conn):
    ctx = krbV.default_context()
    if opts.ccache:
        ccache = krbV.CCache(name='FILE:' + opts.ccache, context=ctx)
    else:
        ccache = ctx.default_ccache()
    cprinc = ccache.principal()
    sprinc = krbV.Principal(name=opts.principal, context=ctx)
    ac = ctx.sendauth(conn,
                      '1.0',
                      options=krbV.AP_OPTS_MUTUAL_REQUIRED,
                      server=sprinc,
                      client=cprinc,
                      ccache=ccache,
                      data='authtest')
    print 'Successfully authenticated via tcp to service: %s' % sprinc.name
    ac.flags = krbV.KRB5_AUTH_CONTEXT_DO_SEQUENCE | krbV.KRB5_AUTH_CONTEXT_DO_TIME
    ac.rcache = ctx.default_rcache()
    ac.genaddrs(
        conn, krbV.KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR
        | krbV.KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR)
    enc_msg = ac.mk_priv(opts.message)
    conn.send(enc_msg)
    enc_resp = conn.recv(4096)
    resp = ac.rd_priv(enc_resp)
    if resp == opts.message:
        print '  Exchanging encrypted messages succeeded'
    conn.close()
コード例 #5
0
def udp_client(opts, sock, addr):
    ctx = krbV.default_context()
    if opts.ccache:
        ccache = krbV.CCache(name='FILE:' + opts.ccache, context=ctx)
    else:
        ccache = ctx.default_ccache()
    cprinc = ccache.principal()
    sprinc = krbV.Principal(name=opts.principal, context=ctx)
    ac = krbV.AuthContext(context=ctx)
    ac.flags = krbV.KRB5_AUTH_CONTEXT_DO_SEQUENCE | krbV.KRB5_AUTH_CONTEXT_DO_TIME
    ac.rcache = ctx.default_rcache()
    ac, req = ctx.mk_req(server=sprinc,
                         client=cprinc,
                         auth_context=ac,
                         ccache=ccache,
                         options=krbV.AP_OPTS_MUTUAL_REQUIRED)
    sock.sendto(req, addr)
    rep, saddr = sock.recvfrom(4096)
    rep_tup = ctx.rd_rep(rep, auth_context=ac)
    print 'Successfully authenticated via udp to service: %s' % sprinc.name
    try:
        addrinfo = socket.getaddrinfo(socket.gethostname(),
                                      sock.getsockname()[1], opts.addr_family)
        localaddr = addrinfo[0][4]
    except socket.gaierror, e:
        gai_error(opts, 'local', socket.gethostname(), e)
コード例 #6
0
def get_sender():
    global config, session, target
    if session and target:
        try:
            return session.sender(target)
        except:
            logging.getLogger('koji.plugin.messagebus').warning('Error getting session, will retry', exc_info=True)
            session = None
            target = None

    config = ConfigParser.SafeConfigParser()
    config.read(CONFIG_FILE)
    if not config.has_option('broker', 'timeout'):
        config.set('broker', 'timeout', '60')
    if not config.has_option('broker', 'heartbeat'):
        config.set('broker', 'heartbeat', '60')

    if config.getboolean('broker', 'ssl'):
        url = 'amqps://'
    else:
        url = 'amqp://'
    auth = config.get('broker', 'auth')
    if auth == 'PLAIN':
        url += config.get('broker', 'username') + '/'
        url += config.get('broker', 'password') + '@'
    elif auth == 'GSSAPI':
        ccname = 'MEMORY:messagebus'
        os.environ['KRB5CCNAME'] = ccname
        ctx = krbV.default_context()
        ccache = krbV.CCache(name=ccname, context=ctx)
        cprinc = krbV.Principal(name=config.get('broker', 'principal'), context=ctx)
        ccache.init(principal=cprinc)
        keytab = krbV.Keytab(name='FILE:' + config.get('broker', 'keytab'), context=ctx)
        ccache.init_creds_keytab(principal=cprinc, keytab=keytab)
    else:
        raise PluginError('unsupported auth type: %s' % auth)

    url += config.get('broker', 'host') + ':'
    url += config.get('broker', 'port')

    conn = Connection.establish(url,
                                sasl_mechanisms=config.get('broker', 'auth'),
                                transport='tls+timeout',
                                timeout=config.getfloat('broker', 'timeout'),
                                heartbeat=config.getint('broker', 'heartbeat'))
    sess = conn.session()
    tgt = """%s;
             { create: sender,
               assert: always,
               node: { type: topic,
                       durable: %s,
                       x-declare: { exchange: "%s",
                                    type: %s } } }""" % \
    (config.get('exchange', 'name'), config.getboolean('exchange', 'durable'),
     config.get('exchange', 'name'), config.get('exchange', 'type'))
    sender = sess.sender(tgt)
    session = sess
    target = tgt

    return sender
コード例 #7
0
ファイル: utils.py プロジェクト: erichuanggit/Nitrate
def refresh_HTTP_credential_cache():
    '''
    Put service ticket into credential cache from service's keytab file.

    Return the credential cache file name.
    '''

    import krbV, os

    keytab_file = st.SERVICE_KEYTAB
    principal_name = st.SERVICE_PRINCIPAL
    # This is the credential cache file, according to the Kerberbos V5 standard
    ccache_file = '/tmp/krb5cc_%d_%d' % (os.getuid(), os.getpid())

    ctx = krbV.default_context()
    princ = krbV.Principal(name=principal_name, context=ctx)
    if keytab_file:
        keytab = krbV.Keytab(name=keytab_file, context=ctx)
    else:
        # According the documentation of MIT Kerberos V5,
        # default keytab file is /etc/krb5.keytab. It might be changed
        # by modifying default_keytab_name in krb5.conf
        keytab = ctx.default_keytab()
    ccache = krbV.CCache(name=ccache_file, context=ctx)

    ccache.init(princ)
    ccache.init_creds_keytab(principal=princ, keytab=keytab)

    return ccache_file
コード例 #8
0
ファイル: ipautil.py プロジェクト: AvidehST/freeipa
def kinit_keytab(principal, keytab, ccache_name, attempts=1):
    """
    Given a ccache_path, keytab file and a principal kinit as that user.

    The optional parameter 'attempts' specifies how many times the credential
    initialization should be attempted in case of non-responsive KDC.
    """
    errors_to_retry = {krbV.KRB5KDC_ERR_SVC_UNAVAILABLE, krbV.KRB5_KDC_UNREACH}
    root_logger.debug("Initializing principal %s using keytab %s" %
                      (principal, keytab))
    root_logger.debug("using ccache %s" % ccache_name)
    for attempt in range(1, attempts + 1):
        try:
            krbcontext = krbV.default_context()
            ktab = krbV.Keytab(name=keytab, context=krbcontext)
            princ = krbV.Principal(name=principal, context=krbcontext)
            ccache = krbV.CCache(name=ccache_name,
                                 context=krbcontext,
                                 primary_principal=princ)
            ccache.init(princ)
            ccache.init_creds_keytab(keytab=ktab, principal=princ)
            root_logger.debug("Attempt %d/%d: success" % (attempt, attempts))
            return
        except krbV.Krb5Error as e:
            if e.args[0] not in errors_to_retry:
                raise
            root_logger.debug("Attempt %d/%d: failed: %s" %
                              (attempt, attempts, e))
            if attempt == attempts:
                root_logger.debug("Maximum number of attempts (%d) reached" %
                                  attempts)
                raise
            root_logger.debug("Waiting 5 seconds before next retry")
            time.sleep(5)
コード例 #9
0
ファイル: krb_utils.py プロジェクト: AvidehST/freeipa
    def __init__(self, ccache):
        '''
        :parameters:
          ccache
            The name of a Kerberos ccache used to hold Kerberos tickets.
        :returns:
          `KRB5_CCache` object encapsulting the ccache.
        '''
        log_mgr.get_logger(self, True)
        self.context = None
        self.scheme = None
        self.name = None
        self.ccache = None
        self.principal = None

        try:
            self.context = krbV.default_context()
            self.scheme, self.name = krb5_parse_ccache(ccache)
            self.ccache = krbV.CCache(name=str(ccache), context=self.context)
            self.principal = self.ccache.principal()
        except krbV.Krb5Error, e:
            error_code = e.args[0]
            message = e.args[1]
            if error_code == KRB5_FCC_NOFILE:
                raise ValueError('"%s", ccache="%s"' % (message, ccache))
            else:
                raise e
コード例 #10
0
 def setUp(self):
     self.context = krbV.default_context()
     self.principal = krbV.Principal(config.service_principal,
                                     context=self.context)
     self.keytab = krbV.Keytab(config.user_keytab_file,
                               context=self.context)
     self.ccache = krbV.CCache(config.user_ccache_file,
                               context=self.context)
コード例 #11
0
    def _login_krbv(self):
        """Login using kerberos credentials (uses python-krbV)."""

        # read default values from settings
        principal = self._conf.get("KRB_PRINCIPAL")
        keytab = self._conf.get("KRB_KEYTAB")
        service = self._conf.get("KRB_SERVICE")
        realm = self._conf.get("KRB_REALM")
        ccache = self._conf.get("KRB_CCACHE")
        proxyuser = self._conf.get("KRB_PROXYUSER")

        import krbV
        ctx = krbV.default_context()

        if ccache is not None:
            ccache = krbV.CCache(name='FILE:' + ccache, context=ctx)
        else:
            ccache = ctx.default_ccache()

        if principal is not None:
            if keytab is not None:
                cprinc = krbV.Principal(name=principal, context=ctx)
                keytab = krbV.Keytab(name=keytab, context=ctx)
                ccache.init(cprinc)
                ccache.init_creds_keytab(principal=cprinc, keytab=keytab)
            else:
                raise ImproperlyConfigured(
                    "Cannot specify a principal without a keytab")
        else:
            # connect using existing credentials
            cprinc = ccache.principal()

        sprinc = krbV.Principal(name=self.get_server_principal(service=service,
                                                               realm=realm),
                                context=ctx)

        ac = krbV.AuthContext(context=ctx)
        ac.flags = krbV.KRB5_AUTH_CONTEXT_DO_SEQUENCE | krbV.KRB5_AUTH_CONTEXT_DO_TIME
        ac.rcache = ctx.default_rcache()

        # create and encode the authentication request
        try:
            ac, req = ctx.mk_req(server=sprinc,
                                 client=cprinc,
                                 auth_context=ac,
                                 ccache=ccache,
                                 options=krbV.AP_OPTS_MUTUAL_REQUIRED)
        except krbV.Krb5Error as ex:
            if getattr(ex, "err_code", None) == -1765328377:
                ex.message += ". Make sure you correctly set KRB_REALM (current value: %s)." % realm
                ex.args = (ex.err_code, ex.message)
            raise ex
        encode_func = base64.encodebytes if hasattr(
            base64, "encodebytes") else base64.encodestring
        req_enc = encode_func(req)

        self._hub.auth.login_krbv(req_enc)
コード例 #12
0
    def testInitCCacheIsNecessary(self):
        ''' Sleep several seconds after initializing credentials cache so that
            it expires.
        '''
        if config.run_under_user_principal:
            init_user_ccache(lifetime='3s')
            time.sleep(5)
            context = krbV.default_context()
            ccache = krbV.CCache(config.user_ccache_file, context=context)
            principal = krbV.Principal(config.user_principal, context=context)
            result = is_initialize_ccache_necessary(context, ccache, principal)
            self.assert_(result)

        init_ccache_using_keytab(lifetime='3s')
        time.sleep(5)
        context = krbV.default_context()
        ccache = krbV.CCache(config.user_ccache_file, context=context)
        principal = krbV.Principal(config.service_principal, context=context)
        result = is_initialize_ccache_necessary(context, ccache, principal)
        self.assert_(result)
コード例 #13
0
 def __init__(self,principal,keytab,ccache_file=None):
     self.context = krbV.default_context()
     self.principal = krbV.Principal(name=principal, context=self.context)
     self.keytab = krbV.Keytab(name=keytab, context=self.context)
     self.ccache_file = ccache_file
     if ccache_file:
         self.ccache_file = ccache_file
         self.ccache = krbV.CCache(name="FILE:" + self.ccache_file, context=self.context, primary_principal=self.principal)
     else:
         self.ccache = self.context.default_ccache(primary_principal=self.principal)
     self.ccache.init(self.principal)
     self.ccache.init_creds_keytab(keytab=self.keytab,principal=self.principal)
コード例 #14
0
 def __init__(self,
              app,
              cache_file=None,
              primary_principal=None,
              keytab=None):
     self.context = krbV.default_context()
     self.primary_principal = primary_principal
     self.keytab = keytab
     if not keytab:
         self.keytab = app.config.get('auth.keytab')
     if self.keytab and not isinstance(self.keytab, krbV.Keytab):
         self.keytab = krbV.Keytab(name=self.keytab, context=self.context)
     if not self.primary_principal:
         self.primary_principal = app.config.get('auth.principal')
     if not self.primary_principal:
         self.primary_principal = None
     if self.primary_principal and not isinstance(self.primary_principal,
                                                  krbV.Principal):
         self.primary_principal = krbV.Principal(
             name=self.primary_principal, context=self.context)
     if self.primary_principal:
         if cache_file:
             self.ccache = krbV.CCache(
                 name="FILE:" + cache_file,
                 context=self.context,
                 primary_principal=self.primary_principal)
         else:
             self.ccache = self.context.default_ccache(
                 primary_principal=self.primary_principal)
     else:
         if cache_file:
             self.ccache = krbV.CCache(name="FILE:" + cache_file,
                                       context=self.context)
         else:
             self.ccache = self.context.default_ccache()
         self.primary_principal = self.ccache.principal()
     if self.keytab: self.reinit()
     self.local_rsa_info = None
     self.rsa_info = {}
コード例 #15
0
 def __init__(self, cache_file=None, primary_principal=None, keytab=None):
     self.context = krbV.default_context()
     self.primary_principal = primary_principal
     self.keytab = keytab
     if self.keytab and not isinstance(self.keytab, krbV.Keytab):
         self.keytab = krbV.Keytab(name=self.keytab, context=self.context)
     if not self.primary_principal and not cache_file:
         raise ValueError('No cache file nor primary principal')
     if self.primary_principal and not isinstance(self.primary_principal, krbV.Principal):
         self.primary_principal = krbV.Principal(name=self.primary_principal, context=self.context)
     if self.primary_principal:
         if cache_file:
             self.ccache = krbV.CCache(name="FILE:"+cache_file, context=self.context,
                                       primary_principal=self.primary_principal)
         else:
             self.ccache = self.context.default_ccache(primary_principal=self.primary_principal)
     else:
         if cache_file:
             self.ccache = krbV.CCache(name="FILE:"+cache_file, context=self.context)
         else:
             self.ccache = self.context.default_ccache()
         self.primary_principal = self.ccache.principal()
     if self.keytab: self.reinit()
コード例 #16
0
def clean_kwargs(context, kwargs):
    ''' Clean argument to related object

    In the case of using Key table, principal is required. keytab_file is
    optional, and default key table file /etc/krb5.keytab is used if
    keytab_file is not provided.

    In the case of initing as a regular user, principal is optional, and
    current user's effective name is used if principal is not provided.

    By default, initialize credentials cache for regular user.
    '''
    cleaned_kwargs = {}

    using_keytab = kwargs.get('using_keytab', False)
    if using_keytab:
        # Principal is required when using key table to initialize
        # credential cache.
        principal_name = kwargs.get('principal', None)
        if principal_name is None:
            raise NameError('Principal is required when using key table.')
        else:
            principal = krbV.Principal(principal_name, context=context)
            cleaned_kwargs['principal'] = principal
        kt_name = kwargs.get('keytab_file', None)
        if kt_name is None:
            keytab = context.default_keytab()
        else:
            keytab = krbV.Keytab(kt_name, context=context)
        cleaned_kwargs['keytab'] = keytab
    else:
        # When initialize credentials cache with a regular user, clean
        # principal has different rule. It will return a valid Principal object
        # always.
        principal_name = kwargs.get('principal', None)
        if principal_name is None:
            principal_name = get_login()
        principal = krbV.Principal(principal_name, context=context)
        cleaned_kwargs['principal'] = principal
    cleaned_kwargs['using_keytab'] = using_keytab

    ccache_file = kwargs.get('ccache_file', None)
    if ccache_file is None:
        ccache = get_default_ccache(context)
    else:
        ccache = krbV.CCache(ccache_file, context=context)
    cleaned_kwargs['ccache'] = ccache

    return cleaned_kwargs
コード例 #17
0
def use_keytab(principal, keytab):
    try:
        tmpdir = tempfile.mkdtemp(prefix="tmp-")
        ccache_file = 'FILE:%s/ccache' % tmpdir
        krbcontext = krbV.default_context()
        principal = str(principal)
        keytab = krbV.Keytab(name=keytab, context=krbcontext)
        principal = krbV.Principal(name=principal, context=krbcontext)
        os.environ['KRB5CCNAME'] = ccache_file
        ccache = krbV.CCache(name=ccache_file,
                             context=krbcontext,
                             primary_principal=principal)
        ccache.init(principal)
        ccache.init_creds_keytab(keytab=keytab, principal=principal)
        conn = ldap2(shared_instance=False,
                     ldap_uri=api.env.ldap_uri,
                     base_dn=api.env.basedn)
        conn.connect(ccache=ccache)
        conn.disconnect()
    except krbV.Krb5Error, e:
        raise StandardError(
            'Unable to bind to LDAP. Error initializing principal %s in %s: %s'
            % (principal.name, keytab, str(e)))
コード例 #18
0
def kinit_hostprincipal(keytab, ccachedir, principal):
    """
    Given a ccache directory and a principal kinit as that user.

    This blindly overwrites the current CCNAME so if you need to save
    it do so before calling this function.

    Thus far this is used to kinit as the local host.
    """
    try:
        ccache_file = 'FILE:%s/ccache' % ccachedir
        krbcontext = krbV.default_context()
        ktab = krbV.Keytab(name=keytab, context=krbcontext)
        princ = krbV.Principal(name=principal, context=krbcontext)
        os.environ['KRB5CCNAME'] = ccache_file
        ccache = krbV.CCache(name=ccache_file,
                             context=krbcontext,
                             primary_principal=princ)
        ccache.init(princ)
        ccache.init_creds_keytab(keytab=ktab, principal=princ)
        return ccache_file
    except krbV.Krb5Error, e:
        raise StandardError('Error initializing principal %s in %s: %s' %
                            (principal, keytab, str(e)))
コード例 #19
0
ファイル: hub.py プロジェクト: joyxu/beaker
    def _login_krbv(self):
        """Login using kerberos credentials (uses python-krbV)."""
        def get_server_principal(service=None, realm=None):
            """Convert hub url to kerberos principal."""
            hostname = urlparse.urlparse(self._hub_url)[1]
            # remove port from hostname
            hostname = hostname.split(":")[0]

            if realm is None:
                # guess realm: last two parts from hostname
                realm = ".".join(hostname.split(".")[-2:]).upper()
            if service is None:
                service = "HTTP"
            return '%s/%s@%s' % (service, hostname, realm)

        # read default values from settings
        principal = self._conf.get("KRB_PRINCIPAL")
        keytab = self._conf.get("KRB_KEYTAB")
        service = self._conf.get("KRB_SERVICE")
        realm = self._conf.get("KRB_REALM")
        ccache = self._conf.get("KRB_CCACHE")
        proxyuser = self._conf.get("PROXY_USER")

        import krbV
        ctx = krbV.default_context()

        if ccache is not None:
            ccache = krbV.CCache(name='FILE:' + ccache, context=ctx)
        elif keytab is not None:
            # If we will be init'ing the ccache using a keytab, we need to
            # always avoid using the default shared ccache, as a workaround for
            # a race condition in krb5_cc_initialize() between unlink() and open()
            # (see RHBZ#1313580).
            ccache_tmpfile = tempfile.NamedTemporaryFile(prefix='krb5cc_bkr_')
            ccache = krbV.CCache(name='FILE:' + ccache_tmpfile.name,
                                 context=ctx)
        else:
            ccache = ctx.default_ccache()

        if principal is not None:
            if keytab is not None:
                cprinc = krbV.Principal(name=principal, context=ctx)
                keytab = krbV.Keytab(name=keytab, context=ctx)
                ccache.init(cprinc)
                ccache.init_creds_keytab(principal=cprinc, keytab=keytab)
            else:
                raise ImproperlyConfigured(
                    "Cannot specify a principal without a keytab")
        else:
            # connect using existing credentials
            cprinc = ccache.principal()

        sprinc = krbV.Principal(name=get_server_principal(service=service,
                                                          realm=realm),
                                context=ctx)

        ac = krbV.AuthContext(context=ctx)
        ac.flags = krbV.KRB5_AUTH_CONTEXT_DO_SEQUENCE | krbV.KRB5_AUTH_CONTEXT_DO_TIME
        ac.rcache = ctx.default_rcache()

        # create and encode the authentication request
        try:
            ac, req = ctx.mk_req(server=sprinc,
                                 client=cprinc,
                                 auth_context=ac,
                                 ccache=ccache,
                                 options=krbV.AP_OPTS_MUTUAL_REQUIRED)
        except krbV.Krb5Error, ex:
            if getattr(ex, "err_code", None) == -1765328377:
                ex.message += ". Make sure you correctly set KRB_REALM (current value: %s)." % realm
                ex.args = (ex.err_code, ex.message)
            raise ex
コード例 #20
0
def get_default_ccache(context):
    if ENV_KRB5CCNAME in os.environ:
        return krbV.CCache(os.environ[ENV_KRB5CCNAME], context=context)
    else:
        return context.default_ccache()
コード例 #21
0
def get_tgt_time_from_ccache(principal_name):
    context = krbV.default_context()
    principal = krbV.Principal(principal_name, context=context)
    ccache = krbV.CCache(config.user_ccache_file, context=context)
    ct = get_tgt_time(context, ccache, principal)
    return ct.endtime
コード例 #22
0
 def _setUp(self):
     self.context = krbV.default_context()
     self.principal = krbV.Principal(config.user_principal,
                                     context=self.context)
     self.ccache = krbV.CCache(config.user_ccache_file,
                               context=self.context)
コード例 #23
0
    def create_connection(self,
                          ccache=None,
                          bind_dn=None,
                          bind_pw='',
                          tls_cacertfile=None,
                          tls_certfile=None,
                          tls_keyfile=None,
                          debug_level=0,
                          autobind=False,
                          serverctrls=None,
                          clientctrls=None):
        """
        Connect to LDAP server.

        Keyword arguments:
        ldapuri -- the LDAP server to connect to
        ccache -- Kerberos V5 ccache object or name
        bind_dn -- dn used to bind to the server
        bind_pw -- password used to bind to the server
        debug_level -- LDAP debug level option
        tls_cacertfile -- TLS CA certificate filename
        tls_certfile -- TLS certificate filename
        tls_keyfile - TLS bind key filename
        autobind - autobind as the current user

        Extends backend.Connectible.create_connection.
        """
        if bind_dn is None:
            bind_dn = DN()
        assert isinstance(bind_dn, DN)
        if tls_cacertfile is not None:
            _ldap.set_option(_ldap.OPT_X_TLS_CACERTFILE, tls_cacertfile)
        if tls_certfile is not None:
            _ldap.set_option(_ldap.OPT_X_TLS_CERTFILE, tls_certfile)
        if tls_keyfile is not None:
            _ldap.set_option(_ldap.OPT_X_TLS_KEYFILE, tls_keyfile)

        if debug_level:
            _ldap.set_option(_ldap.OPT_DEBUG_LEVEL, debug_level)

        object.__setattr__(self, '_force_schema_updates', self.api.env.context
                           in ('installer', 'updates'))
        LDAPClient._connect(self)
        conn = self._conn

        with self.error_handler():
            if self.ldap_uri.startswith('ldapi://') and ccache:
                conn.set_option(_ldap.OPT_HOST_NAME, self.api.env.host)
            minssf = conn.get_option(_ldap.OPT_X_SASL_SSF_MIN)
            maxssf = conn.get_option(_ldap.OPT_X_SASL_SSF_MAX)
            # Always connect with at least an SSF of 56, confidentiality
            # This also protects us from a broken ldap.conf
            if minssf < 56:
                minssf = 56
                conn.set_option(_ldap.OPT_X_SASL_SSF_MIN, minssf)
                if maxssf < minssf:
                    conn.set_option(_ldap.OPT_X_SASL_SSF_MAX, minssf)

        if ccache is not None:
            if isinstance(ccache, krbV.CCache):
                principal = ccache.principal().name
                # Get a fully qualified CCACHE name (schema+name)
                # As we do not use the krbV.CCache object later,
                # we can safely overwrite it
                ccache = "%(type)s:%(name)s" % dict(type=ccache.type,
                                                    name=ccache.name)
            else:
                principal = krbV.CCache(
                    name=ccache,
                    context=krbV.default_context()).principal().name

            os.environ['KRB5CCNAME'] = ccache
            self.gssapi_bind(server_controls=serverctrls,
                             client_controls=clientctrls)
            setattr(context, 'principal', principal)
        else:
            # no kerberos ccache, use simple bind or external sasl
            if autobind:
                pent = pwd.getpwuid(os.geteuid())
                self.external_bind(pent.pw_name,
                                   server_controls=serverctrls,
                                   client_controls=clientctrls)
            else:
                self.simple_bind(bind_dn,
                                 bind_pw,
                                 server_controls=serverctrls,
                                 client_controls=clientctrls)

        return conn
コード例 #24
0
ファイル: kerberos.py プロジェクト: AvidehST/freeipa
 def __get_ccache(self, ccname):
     """
     Return the ``krbV.CCache`` for the ``ccname`` credential ccache.
     """
     return krbV.CCache(ccname)
コード例 #25
0
    def _login_krbv(self):
        """Login using kerberos credentials (uses python-krbV)."""
        def get_server_principal(service=None, realm=None):
            """Convert hub url to kerberos principal."""
            hostname = urlparse.urlparse(self._hub_url)[1]
            # remove port from hostname
            hostname = hostname.split(":")[0]

            if realm is None:
                # guess realm: last two parts from hostname
                realm = ".".join(hostname.split(".")[-2:]).upper()
            if service is None:
                service = "HTTP"
            return '%s/%s@%s' % (service, hostname, realm)

        # read default values from settings
        principal = self._conf.get("KRB_PRINCIPAL")
        keytab = self._conf.get("KRB_KEYTAB")
        service = self._conf.get("KRB_SERVICE")
        realm = self._conf.get("KRB_REALM")
        ccache = self._conf.get("KRB_CCACHE")
        proxyuser = self._conf.get("KRB_PROXYUSER")

        import krbV
        ctx = krbV.default_context()

        if ccache is not None:
            ccache = krbV.CCache(name='FILE:' + ccache, context=ctx)
        else:
            ccache = ctx.default_ccache()

        if principal is not None:
            if keytab is not None:
                cprinc = krbV.Principal(name=principal, context=ctx)
                keytab = krbV.Keytab(name=keytab, context=ctx)
                ccache.init(cprinc)
                ccache.init_creds_keytab(principal=cprinc, keytab=keytab)
            else:
                raise ImproperlyConfigured(
                    "Cannot specify a principal without a keytab")
        else:
            # connect using existing credentials
            cprinc = ccache.principal()

        sprinc = krbV.Principal(name=get_server_principal(service=service,
                                                          realm=realm),
                                context=ctx)

        ac = krbV.AuthContext(context=ctx)
        ac.flags = krbV.KRB5_AUTH_CONTEXT_DO_SEQUENCE | krbV.KRB5_AUTH_CONTEXT_DO_TIME
        ac.rcache = ctx.default_rcache()

        # create and encode the authentication request
        try:
            ac, req = ctx.mk_req(server=sprinc,
                                 client=cprinc,
                                 auth_context=ac,
                                 ccache=ccache,
                                 options=krbV.AP_OPTS_MUTUAL_REQUIRED)
        except krbV.Krb5Error as ex:
            if getattr(ex, "err_code", None) == -1765328377:
                ex.message += ". Make sure you correctly set KRB_REALM (current value: %s)." % realm
                ex.args = (ex.err_code, ex.message)
            raise ex
        req_enc = base64.encodestring(req)

        self._hub.auth.login_krbv(req_enc)