Example #1
0
/* The caller is responsible for unbinding the connection if ld is not NULL */
static LDAP *
connect_ldap(const char *hostname, const char *binddn, const char *bindpw) {
    LDAP *ld = NULL;
    int ssl = LDAP_OPT_X_TLS_HARD;
    int version = LDAP_VERSION3;
    int ret;
    int ldapdebug = 0;
    char *uri;
    struct berval bindpw_bv;

    if (debug) {
        ldapdebug=2;
        ret = ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &ldapdebug);
    }

    if (ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, CAFILE) != LDAP_OPT_SUCCESS)
        goto fail;

    ret = asprintf(&uri, "ldaps://%s:636", hostname);
    if (ret == -1) {
        fprintf(stderr, _("Out of memory!"));
        goto fail;
    }

    ret = ldap_initialize(&ld, uri);
    free(uri);
    if(ret != LDAP_SUCCESS) {
        fprintf(stderr, _("Unable to initialize connection to ldap server: %s"),
                        ldap_err2string(ret));
        goto fail;
    }

    if (ldap_set_option(ld, LDAP_OPT_X_TLS, &ssl) != LDAP_OPT_SUCCESS) {
        fprintf(stderr, _("Unable to enable SSL in LDAP\n"));
        goto fail;
    }

    /* Don't do DNS canonicalization */
    ret = ldap_set_option(ld, LDAP_OPT_X_SASL_NOCANON, LDAP_OPT_ON);
    if (ret != LDAP_SUCCESS) {
        fprintf(stderr, _("Unable to set LDAP_OPT_X_SASL_NOCANON\n"));
        goto fail;
    }

    ret = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
    if (ret != LDAP_SUCCESS) {
        fprintf(stderr, _("Unable to set LDAP version\n"));
        goto fail;
    }

    if (bindpw) {
        bindpw_bv.bv_val = discard_const(bindpw);
        bindpw_bv.bv_len = strlen(bindpw);
    } else {
        bindpw_bv.bv_val = NULL;
        bindpw_bv.bv_len = 0;
    }

    ret = ldap_sasl_bind_s(ld, binddn, LDAP_SASL_SIMPLE, &bindpw_bv,
                           NULL, NULL, NULL);

    if (ret != LDAP_SUCCESS) {
        int err;

        ldap_get_option(ld, LDAP_OPT_RESULT_CODE, &err);
        if (debug)
            fprintf(stderr, _("Bind failed: %s\n"), ldap_err2string(err));
        goto fail;
    }

    return ld;

fail:
    if (ld != NULL) {
        ldap_unbind_ext(ld, NULL, NULL);
    }
    return NULL;
}
Example #2
0
/*
 * asyncmeta_single_bind
 *
 * attempts to perform a bind with creds
 */
static int
asyncmeta_single_bind(
	Operation		*op,
	SlapReply		*rs,
	a_metaconn_t		*mc,
	int			candidate )
{
	a_metainfo_t		*mi = mc->mc_info;
	a_metatarget_t		*mt = mi->mi_targets[ candidate ];
	struct berval		mdn = BER_BVNULL;
	a_metasingleconn_t	*msc = &mc->mc_conns[ candidate ];
	int			msgid;
	a_dncookie		dc;
	struct berval		save_o_dn;
	int			save_o_do_not_cache;
	LDAPControl		**ctrls = NULL;

	if ( !BER_BVISNULL( &msc->msc_bound_ndn ) ) {
		ch_free( msc->msc_bound_ndn.bv_val );
		BER_BVZERO( &msc->msc_bound_ndn );
	}

	if ( !BER_BVISNULL( &msc->msc_cred ) ) {
		/* destroy sensitive data */
		memset( msc->msc_cred.bv_val, 0, msc->msc_cred.bv_len );
		ch_free( msc->msc_cred.bv_val );
		BER_BVZERO( &msc->msc_cred );
	}

	/*
	 * Rewrite the bind dn if needed
	 */
	dc.target = mt;
	dc.conn = op->o_conn;
	dc.rs = rs;
	dc.ctx = "bindDN";

	if ( asyncmeta_dn_massage( &dc, &op->o_req_dn, &mdn ) ) {
		rs->sr_text = "DN rewrite error";
		rs->sr_err = LDAP_OTHER;
		return rs->sr_err;
	}

	/* don't add proxyAuthz; set the bindDN */
	save_o_dn = op->o_dn;
	save_o_do_not_cache = op->o_do_not_cache;
	op->o_do_not_cache = 1;
	op->o_dn = op->o_req_dn;

	ctrls = op->o_ctrls;
	rs->sr_err = asyncmeta_controls_add( op, rs, mc, candidate, &ctrls );
	op->o_dn = save_o_dn;
	op->o_do_not_cache = save_o_do_not_cache;
	if ( rs->sr_err != LDAP_SUCCESS ) {
		goto return_results;
	}

	/* FIXME: this fixes the bind problem right now; we need
	 * to use the asynchronous version to get the "matched"
	 * and more in case of failure ... */
	/* FIXME: should we check if at least some of the op->o_ctrls
	 * can/should be passed? */
	for (;;) {
		rs->sr_err = ldap_sasl_bind( msc->msc_ld, mdn.bv_val,
			LDAP_SASL_SIMPLE, &op->orb_cred,
			ctrls, NULL, &msgid );
		if ( rs->sr_err != LDAP_X_CONNECTING ) {
			break;
		}
		ldap_pvt_thread_yield();
	}

	mi->mi_ldap_extra->controls_free( op, rs, &ctrls );

	asyncmeta_bind_op_result( op, rs, mc, candidate, msgid, LDAP_BACK_DONTSEND, 1 );
	if ( rs->sr_err != LDAP_SUCCESS ) {
		goto return_results;
	}

	/* If defined, proxyAuthz will be used also when
	 * back-ldap is the authorizing backend; for this
	 * purpose, a successful bind is followed by a
	 * bind with the configured identity assertion */
	/* NOTE: use with care */
	if ( mt->mt_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
		asyncmeta_proxy_authz_bind( mc, candidate, op, rs, LDAP_BACK_SENDERR, 1 );
		if ( !LDAP_BACK_CONN_ISBOUND( msc ) ) {
			goto return_results;
		}
		goto cache_refresh;
	}

	ber_bvreplace( &msc->msc_bound_ndn, &op->o_req_ndn );
	LDAP_BACK_CONN_ISBOUND_SET( msc );
	mc->mc_authz_target = candidate;

	if ( META_BACK_TGT_SAVECRED( mt ) ) {
		if ( !BER_BVISNULL( &msc->msc_cred ) ) {
			memset( msc->msc_cred.bv_val, 0,
				msc->msc_cred.bv_len );
		}
		ber_bvreplace( &msc->msc_cred, &op->orb_cred );
		ldap_set_rebind_proc( msc->msc_ld, mt->mt_rebind_f, msc );
	}

cache_refresh:;
	if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED
			&& !BER_BVISEMPTY( &op->o_req_ndn ) )
	{
		( void )asyncmeta_dncache_update_entry( &mi->mi_cache,
				&op->o_req_ndn, candidate );
	}

return_results:;
	if ( mdn.bv_val != op->o_req_dn.bv_val ) {
		free( mdn.bv_val );
	}

	if ( META_BACK_TGT_QUARANTINE( mt ) ) {
		asyncmeta_quarantine( op, mi, rs, candidate );
	}
	ldap_unbind_ext( msc->msc_ld, NULL, NULL );
	msc->msc_ld = NULL;
	ldap_ld_free( msc->msc_ldr, 0, NULL, NULL );
	msc->msc_ldr = NULL;
	return rs->sr_err;
}
Example #3
0
/*
 * Function called during initialization phase => no need to use the GdaWorker object
 *
 * Using @url and @username, performs the following tasks:
 * - bind to the LDAP server anonymously
 * - search the directory to identify the entry for the provided user name,
 *   filter: (&(uid=##uid)(objectclass=inetOrgPerson))
 * - if one and only one entry is returned, get the DN of the entry and check that the UID is correct
 *
 * If all the steps are right, it returns the DN of the identified entry as a new string.
 */
static gchar *
fetch_user_dn (const gchar *url, const gchar *base, const gchar *username, LdapAuthMapping *mapping)
{
	LDAP *ld;
	int res;
	int version = LDAP_VERSION3;
	gchar *dn = NULL;
	LDAPMessage *msg = NULL;

	if (! username)
		return NULL;

	res = ldap_initialize (&ld, url);
	if (res != LDAP_SUCCESS)
		return NULL;

	res = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &version);
        if (res != LDAP_SUCCESS) {
		if (res == LDAP_PROTOCOL_ERROR) {
			version = LDAP_VERSION2;
			res = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &version);
		}
		if (res != LDAP_SUCCESS)
			goto out;
        }

	struct berval cred;
        memset (&cred, 0, sizeof (cred));
	res = ldap_sasl_bind_s (ld, NULL, NULL, &cred, NULL, NULL, NULL);
	if (res != LDAP_SUCCESS)
		goto out;

	gchar *filter;
	gchar *attributes[] = {NULL, NULL};
	attributes[0] = mapping->attribute;
	filter = g_strdup_printf (mapping->filter_format, username);
	res = ldap_search_ext_s (ld, base, LDAP_SCOPE_SUBTREE,
				 filter, attributes, 0,
				 NULL, NULL, NULL, 2, &msg);
	g_free (filter);
	if (res != LDAP_SUCCESS)
		goto out;

	LDAPMessage *ldap_row;
	for (ldap_row = ldap_first_entry (ld, msg);
	     ldap_row;
	     ldap_row = ldap_next_entry (ld, ldap_row)) {
		char *attr, *uid;
		attr = ldap_get_dn (ld, ldap_row);
		if (attr) {
			BerElement* ber;
			for (uid = ldap_first_attribute (ld, ldap_row, &ber);
			     uid;
			     uid = ldap_next_attribute (ld, ldap_row, ber)) {
				BerValue **bvals;
				bvals = ldap_get_values_len (ld, ldap_row, uid);
				if (!bvals || !bvals[0] || bvals[1] || strcmp (bvals[0]->bv_val, username)) {
					g_free (dn);
					dn = NULL;
				}
				ldap_value_free_len (bvals);
				ldap_memfree (uid);
			}

			if (dn) {
				/* more than 1 entry => unique DN could not be identified */
				g_free (dn);
				dn = NULL;
				goto out;
			}

			dn = g_strdup (attr);
			ldap_memfree (attr);
		}
	}

 out:
	if (msg)
		ldap_msgfree (msg);
	ldap_unbind_ext (ld, NULL, NULL);
	/*g_print ("Identified DN: [%s]\n", dn);*/
	return dn;
}
Example #4
0
static int
libbalsa_address_book_ldap_open_connection(LibBalsaAddressBookLdap * ab)
{
    int result;
    static const int version = LDAP_VERSION3;
    gboolean v3_enabled;
    LibBalsaAddressBook *lbab = LIBBALSA_ADDRESS_BOOK(ab);

    g_return_val_if_fail(ab->host != NULL, FALSE);

    ldap_initialize(&ab->directory, ab->host);
    if (ab->directory == NULL) { /* very unlikely... */
        libbalsa_address_book_set_status(lbab, g_strdup("Host not found"));
	return LDAP_SERVER_DOWN;
    }
    /* ignore error if the V3 LDAP cannot be set */
    v3_enabled = 
        ldap_set_option(ab->directory, LDAP_OPT_PROTOCOL_VERSION, &version)
       == LDAP_OPT_SUCCESS;
    if(!v3_enabled) printf("Too old LDAP server - interaction may fail.\n");
    if(v3_enabled && ab->enable_tls) {
#ifdef HAVE_LDAP_TLS
        /* turn TLS on  but what if we have SSL already on? */
        result = ldap_start_tls_s(ab->directory, NULL, NULL);
        if(result != LDAP_SUCCESS) {
            ldap_unbind_ext(ab->directory, NULL, NULL);
            ab->directory = NULL;
            libbalsa_address_book_set_status
                (lbab, g_strdup(ldap_err2string(result)));
            return result;
        }
#else /* HAVE_LDAP_TLS */
     libbalsa_address_book_set_status(lbab,
                                      _("TLS requested but not compiled in"));
     return LDAP_INAPPRIOPRIATE_AUTH;
#endif /* HAVE_LDAP_TLS */
    }

#ifdef HAVE_CYRUS_SASL
    result = ldap_sasl_interactive_bind_s(ab->directory, ab->bind_dn, NULL,
                                          NULL, NULL,
                                          LDAP_SASL_QUIET, abl_interact, ab);
#else /* HAVE_CYRUS_SASL */
    {
     struct berval   cred;   
     cred.bv_val = ab->passwd;
     cred.bv_len = ab->passwd ? strlen(ab->passwd) : 0;
     result = ldap_sasl_bind_s(ab->directory, ab->bind_dn, NULL, &cred,
                              NULL, NULL, NULL);
    }
#endif /* HAVE_CYRUS_SASL */

    /* do not follow referrals (OpenLDAP binds anonymously here, which will usually
     * fail */
    if (result == LDAP_SUCCESS)
	result = ldap_set_option(ab->directory, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);

    if (result != LDAP_SUCCESS) {
        libbalsa_address_book_set_status(lbab,
                                         g_strdup(ldap_err2string(result)));
	ldap_unbind_ext(ab->directory, NULL, NULL);
	ab->directory = NULL;
    }
    return result;
}
Example #5
0
static void
do_random( char *uri, char *manager, struct berval *passwd,
	char *sbase, char *filter, char **srchattrs, int noattrs, int nobind,
	int innerloop, int maxretries, int delay, int force, int chaserefs )
{
	LDAP	*ld = NULL;
	int  	i = 0, do_retry = maxretries;
	char	*attrs[ 2 ];
	int     rc = LDAP_SUCCESS;
	int	version = LDAP_VERSION3;
	int	nvalues = 0;
	char	**values = NULL;
	LDAPMessage *res = NULL, *e = NULL;

	attrs[ 0 ] = LDAP_NO_ATTRS;
	attrs[ 1 ] = NULL;

	ldap_initialize( &ld, uri );
	if ( ld == NULL ) {
		tester_perror( "ldap_initialize", NULL );
		exit( EXIT_FAILURE );
	}

	(void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version ); 
	(void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
		chaserefs ? LDAP_OPT_ON : LDAP_OPT_OFF );

	if ( do_retry == maxretries ) {
		fprintf( stderr, "PID=%ld - Read(%d): base=\"%s\", filter=\"%s\".\n",
				(long) pid, innerloop, sbase, filter );
	}

	if ( nobind == 0 ) {
		rc = ldap_sasl_bind_s( ld, manager, LDAP_SASL_SIMPLE, passwd, NULL, NULL, NULL );
		if ( rc != LDAP_SUCCESS ) {
			tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
			switch ( rc ) {
			case LDAP_BUSY:
			case LDAP_UNAVAILABLE:
			/* fallthru */
			default:
				break;
			}
			exit( EXIT_FAILURE );
		}
	}

	rc = ldap_search_ext_s( ld, sbase, LDAP_SCOPE_SUBTREE,
		filter, attrs, 0, NULL, NULL, NULL, LDAP_NO_LIMIT, &res );
	switch ( rc ) {
	case LDAP_SIZELIMIT_EXCEEDED:
	case LDAP_TIMELIMIT_EXCEEDED:
	case LDAP_SUCCESS:
		nvalues = ldap_count_entries( ld, res );
		if ( nvalues == 0 ) {
			if ( rc ) {
				tester_ldap_error( ld, "ldap_search_ext_s", NULL );
			}
			break;
		}

		values = malloc( ( nvalues + 1 ) * sizeof( char * ) );
		for ( i = 0, e = ldap_first_entry( ld, res ); e != NULL; i++, e = ldap_next_entry( ld, e ) )
		{
			values[ i ] = ldap_get_dn( ld, e );
		}
		values[ i ] = NULL;

		ldap_msgfree( res );

		if ( do_retry == maxretries ) {
			fprintf( stderr, "  PID=%ld - Read base=\"%s\" filter=\"%s\" got %d values.\n",
				(long) pid, sbase, filter, nvalues );
		}

		for ( i = 0; i < innerloop; i++ ) {
#if 0	/* use high-order bits for better randomness (Numerical Recipes in "C") */
			int	r = rand() % nvalues;
#endif
			int	r = ((double)nvalues)*rand()/(RAND_MAX + 1.0);

			do_read( uri, manager, passwd, values[ r ], &ld,
				srchattrs, noattrs, nobind, 1, maxretries,
				delay, force, chaserefs );
		}
		free( values );
		break;

	default:
		tester_ldap_error( ld, "ldap_search_ext_s", NULL );
		break;
	}

	fprintf( stderr, "  PID=%ld - Read done (%d).\n", (long) pid, rc );

	if ( ld != NULL ) {
		ldap_unbind_ext( ld, NULL, NULL );
	}
}
int
ldap_unbind_s( LDAP *ld )
{
	return( ldap_unbind_ext( ld, NULL, NULL ) );
}
Example #7
0
static int ipa_ldap_bind(const char *server_name, krb5_principal bind_princ,
			 const char *bind_dn, const char *bind_pw, LDAP **_ld)
{
    char *msg = NULL;
    struct berval bv;
    int version;
    LDAP *ld;
    int ssl;
    int ret;

    /* TODO: support referrals ? */
    if (bind_dn) {
        ret = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ca_cert_file);
        if (ret != LDAP_OPT_SUCCESS) {
            fprintf(stderr, _("Unable to set LDAP_OPT_X_TLS_CERTIFICATE\n"));
            return ret;
        }

        ret = ipa_ldap_init(&ld, "ldaps", server_name, 636);
        if (ret != LDAP_SUCCESS) {
            fprintf(stderr, _("Unable to init for ldaps(636) connection\n"));
            return ret;
        }

        ssl = LDAP_OPT_X_TLS_HARD;;
        ret = ldap_set_option(ld, LDAP_OPT_X_TLS, &ssl);
        if (ret != LDAP_OPT_SUCCESS) {
            fprintf(stderr, _("Unable to set LDAP_OPT_X_TLS\n"));
            goto done;
        }
    } else {
        ret = ipa_ldap_init(&ld, "ldap", server_name, 389);
        if (ret != LDAP_SUCCESS) {
            fprintf(stderr, _("Unable to init for ldap(389) connection\n"));
            return ret;
        }
    }

    if (ld == NULL) {
        fprintf(stderr, _("Unable to initialize ldap library!\n"));
        return LDAP_OPERATIONS_ERROR;
    }

#ifdef LDAP_OPT_X_SASL_NOCANON
    /* Don't do DNS canonicalization */
    ret = ldap_set_option(ld, LDAP_OPT_X_SASL_NOCANON, LDAP_OPT_ON);
    if (ret != LDAP_SUCCESS) {
	fprintf(stderr, _("Unable to set LDAP_OPT_X_SASL_NOCANON\n"));
        goto done;
    }
#endif

    version = LDAP_VERSION3;
    ret = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
    if (ret != LDAP_SUCCESS) {
	fprintf(stderr, _("Unable to set LDAP_OPT_PROTOCOL_VERSION\n"));
	goto done;
    }

    if (bind_dn) {
        bv.bv_val = discard_const(bind_pw);
        bv.bv_len = strlen(bind_pw);

        ret = ldap_sasl_bind_s(ld, bind_dn, LDAP_SASL_SIMPLE,
                               &bv, NULL, NULL, NULL);
        if (ret != LDAP_SUCCESS) {
            fprintf(stderr, _("Simple bind failed\n"));
            goto done;
        }
    } else {
        ret = ldap_sasl_interactive_bind_s(ld, NULL, "GSSAPI",
                                           NULL, NULL, LDAP_SASL_QUIET,
                                           ldap_sasl_interact, bind_princ);
        if (ret != LDAP_SUCCESS) {
#ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE
            ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
#endif
            fprintf(stderr, "SASL Bind failed %s (%d) %s!\n",
                            ldap_err2string(ret), ret, msg ? msg : "");
            goto done;
        }
    }

    ret = LDAP_SUCCESS;

done:
    if (ret != LDAP_SUCCESS) {
        if (ld) ldap_unbind_ext(ld, NULL, NULL);
    } else {
        *_ld = ld;
    }
    return ret;
}
static int
check_auth(LD_session *session, char *login, char *password, char *fullname) {
	int rc = 0, count = 0;
	char username[MAXFILTERSTR];
	char logbuf[MAXLOGBUF];
	LDAPMessage *res, *entry;
	char *attr;
	BerElement * ber;
        struct berval **list_of_values;
        struct berval value;
	char *userdn, *validgroups, *fn;
	char filter[MAXFILTERSTR];

	/* Check authorization */
	memset(filter, 0, 100);
	snprintf(filter, MAXLOGBUF, "(&(objectClass=posixGroup)(memberUid=%s))", login);

	struct berval cred;
	struct berval *msgidp=NULL;
	cred.bv_val = password;
	cred.bv_len = strlen(password);

#if LDAP_API_VERSION > 3000
	if((rc = ldap_sasl_bind_s(session->sess, fullname, ldap_authorization_type, &cred, NULL, NULL, NULL))!=LDAP_SUCCESS) {
		snprintf(logbuf, MAXLOGBUF, "Ldap server %s authentificate with method %s failed: %s", ldap_authorization_host, ldap_authorization_type, ldap_err2string(rc));	
		ldap_log(LOG_DEBUG, logbuf);
		return RETURN_FALSE;
	};
#else
	if((rc = ldap_bind_s(session->sess, fullname, password, LDAP_AUTH_SIMPLE))!=LDAP_SUCCESS) {
		snprintf(logbuf, MAXLOGBUF, "Ldap server %s authentificate failed: %s", ldap_authorization_host, ldap_err2string(rc));	
		ldap_log(LOG_DEBUG, logbuf);
		return RETURN_FALSE;
	}
#endif

	if ((rc = ldap_search_ext_s(session->sess, ldap_authorization_basedn, LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT, &res)) != LDAP_SUCCESS) {
#if LDAP_API_VERSION > 3000
		ldap_unbind_ext(session->sess, NULL, NULL);
#else	
		ldap_unbind(session->sess);
#endif
	        return RETURN_TRUE;
	}
	
	for (entry = ldap_first_entry(session->sess,res); entry!=NULL && count<ldap_count_messages(session->sess, res); entry=ldap_next_entry(session->sess, res)) {
		count++;
		for(attr = ldap_first_attribute(session->sess,entry,&ber); attr != NULL ; attr=ldap_next_attribute(session->sess,entry,ber)) {
			snprintf(logbuf, MAXLOGBUF, "Found attribute %s", attr); 	
			ldap_log(LOG_DEBUG, logbuf); 
			if (strcmp(attr, "cn"))
				continue;
			if ((list_of_values = ldap_get_values_len(session->sess, entry, attr)) != NULL ) {
				value = *list_of_values[0];
				char temp[MAXGROUPLIST];
				memset(temp, 0, MAXGROUPLIST);
				if (ldap_authorization_validgroups) {
				    strcpy(temp, ldap_authorization_validgroups);
				    validgroups = strtok(temp, ",");
				    while (validgroups != NULL)
				    {
					snprintf(logbuf, MAXLOGBUF, "Attribute value validgroups ? value.bv_val >> %s ? %s", validgroups, value.bv_val); 	
					ldap_log(LOG_DEBUG, logbuf); 
					if (!strcmp(validgroups, value.bv_val))
					{
					    ldap_msgfree(res);
#if LDAP_API_VERSION > 3000
					    ldap_unbind_ext(session->sess, NULL, NULL);
#else	
					    ldap_unbind(session->sess);
#endif
					    fn = (char *)malloc(strlen(value.bv_val));
					    strcpy(fn, value.bv_val);
					    return RETURN_TRUE;
					}
					validgroups = strtok (NULL, ",");
				    }
				    printf("VAL: %s\n", value.bv_val);
				    ldap_value_free_len( list_of_values );
				}
			}
		}
		res = ldap_next_message(session->sess, res);
	};
	ldap_msgfree(res);
#if LDAP_API_VERSION > 3000
	ldap_unbind_ext(session->sess, NULL, NULL);
#else	
	ldap_unbind(session->sess);
#endif
	return RETURN_FALSE;
}
Example #9
0
int
main( int argc, char **argv )
{
	int		i;
	char		*uri = NULL;
	char		*host = "localhost";
	int		port = -1;
	char		*manager = NULL;
	struct berval	passwd = { 0, NULL };
	char		outstr[BUFSIZ];
	int		ptpass;
	int		testfail = 0;


	tester_init( "slapd-mtread", TESTER_READ );

	/* by default, tolerate referrals and no such object */
	tester_ignore_str2errlist( "REFERRAL,NO_SUCH_OBJECT" );

	while ( (i = getopt( argc, argv, "ACc:D:e:Ff:H:h:i:L:l:M:m:p:r:t:T:w:v" )) != EOF ) {
		switch ( i ) {
		case 'A':
			noattrs++;
			break;

		case 'C':
			chaserefs++;
			break;

		case 'H':		/* the server uri */
			uri = strdup( optarg );
			break;

		case 'h':		/* the servers host */
			host = strdup( optarg );
			break;

		case 'i':
			tester_ignore_str2errlist( optarg );
			break;

		case 'N':
			nobind++;
			break;

		case 'v':
			verbose++;
			break;

		case 'p':		/* the servers port */
			if ( lutil_atoi( &port, optarg ) != 0 ) {
				usage( argv[0] );
			}
			break;

		case 'D':		/* the servers manager */
			manager = strdup( optarg );
			break;

		case 'w':		/* the server managers password */
			passwd.bv_val = strdup( optarg );
			passwd.bv_len = strlen( optarg );
			memset( optarg, '*', passwd.bv_len );
			break;

		case 'c':		/* the number of connections */
			if ( lutil_atoi( &noconns, optarg ) != 0 ) {
				usage( argv[0] );
			}
			break;

		case 'e':		/* DN to search for */
			entry = strdup( optarg );
			break;

		case 'f':		/* the search request */
			filter = strdup( optarg );
			break;

		case 'F':
			force++;
			break;

		case 'l':		/* the number of loops */
			if ( lutil_atoi( &loops, optarg ) != 0 ) {
				usage( argv[0] );
			}
			break;

		case 'L':		/* the number of outerloops */
			if ( lutil_atoi( &outerloops, optarg ) != 0 ) {
				usage( argv[0] );
			}
			break;

		case 'M':		/* the number of R/W threads */
			if ( lutil_atoi( &rwthreads, optarg ) != 0 ) {
				usage( argv[0] );
			}
			if (rwthreads > MAX_THREAD)
				rwthreads = MAX_THREAD;
			break;

		case 'm':		/* the number of threads */
			if ( lutil_atoi( &threads, optarg ) != 0 ) {
				usage( argv[0] );
			}
			if (threads > MAX_THREAD)
				threads = MAX_THREAD;
			break;

		case 'r':		/* the number of retries */
			if ( lutil_atoi( &retries, optarg ) != 0 ) {
				usage( argv[0] );
			}
			break;

		case 't':		/* delay in seconds */
			if ( lutil_atoi( &delay, optarg ) != 0 ) {
				usage( argv[0] );
			}
			break;

		case 'T':
			attrs = ldap_str2charray( optarg, "," );
			if ( attrs == NULL ) {
				usage( argv[0] );
			}
			break;

		default:
			usage( argv[0] );
			break;
		}
	}

	if (( entry == NULL ) || ( port == -1 && uri == NULL ))
		usage( argv[0] );

	if ( *entry == '\0' ) {
		fprintf( stderr, "%s: invalid EMPTY entry DN.\n",
				argv[0] );
		exit( EXIT_FAILURE );
	}

	if ( argv[optind] != NULL ) {
		attrs = &argv[optind];
	}

	if (noconns < 1)
		noconns = 1;
	if (noconns > MAXCONN)
		noconns = MAXCONN;
	lds = (LDAP **) calloc( sizeof(LDAP *), noconns);
	if (lds == NULL) {
		fprintf( stderr, "%s: Memory error: calloc noconns.\n",
				argv[0] );
		exit( EXIT_FAILURE );
	}

	uri = tester_uri( uri, host, port );
	/* One connection and one connection only */
	do_conn( uri, manager, &passwd, &ld, nobind, retries, 0 );
	lds[0] = ld;
	for(i = 1; i < noconns; i++) {
		do_conn( uri, manager, &passwd, &lds[i], nobind, retries, i );
	}

	ldap_pvt_thread_initialize();

	snprintf(outstr, BUFSIZ, "MT Test Start: conns: %d (%s)", noconns, uri);
	tester_error(outstr);
	snprintf(outstr, BUFSIZ, "Threads: RO: %d RW: %d", threads, rwthreads);
	tester_error(outstr);

	/* Set up read only threads */
	for ( i = 0; i < threads; i++ ) {
		ldap_pvt_thread_create( &rtid[i], 0, do_onethread, &rtid[i]);
		snprintf(outstr, BUFSIZ, "Created RO thread %d", i);
		thread_verbose(-1, outstr);
	}
	/* Set up read/write threads */
	for ( i = 0; i < rwthreads; i++ ) {
		ldap_pvt_thread_create( &rwtid[i], 0, do_onerwthread, &rwtid[i]);
		snprintf(outstr, BUFSIZ, "Created RW thread %d", i + MAX_THREAD);
		thread_verbose(-1, outstr);
	}

	ptpass =  outerloops * loops;

	/* wait for read only threads to complete */
	for ( i = 0; i < threads; i++ )
		ldap_pvt_thread_join(rtid[i], NULL);
	/* wait for read/write threads to complete */
	for ( i = 0; i < rwthreads; i++ )
		ldap_pvt_thread_join(rwtid[i], NULL);

	for(i = 0; i < noconns; i++) {
		if ( lds[i] != NULL ) {
			ldap_unbind_ext( lds[i], NULL, NULL );
		}
	}
	free( lds );

	for ( i = 0; i < threads; i++ ) {
		snprintf(outstr, BUFSIZ, "RO thread %d pass=%d fail=%d", i,
			rt_pass[i], rt_fail[i]);
		tester_error(outstr);
		if (rt_fail[i] != 0 || rt_pass[i] != ptpass) {
			snprintf(outstr, BUFSIZ, "FAIL RO thread %d", i);
			tester_error(outstr);
			testfail++;
		}
	}
	for ( i = 0; i < rwthreads; i++ ) {
		snprintf(outstr, BUFSIZ, "RW thread %d pass=%d fail=%d", i + MAX_THREAD,
			rwt_pass[i], rwt_fail[i]);
		tester_error(outstr);
		if (rwt_fail[i] != 0 || rwt_pass[i] != ptpass) {
			snprintf(outstr, BUFSIZ, "FAIL RW thread %d", i);
			tester_error(outstr);
			testfail++;
		}
	}
	snprintf(outstr, BUFSIZ, "MT Test complete" );
	tester_error(outstr);

	if (testfail)
		exit( EXIT_FAILURE );
	exit( EXIT_SUCCESS );
}
Example #10
0
static void
do_modrdn( char *uri, char *manager,
	struct berval *passwd, char *entry, int maxloop, int maxretries,
	int delay, int friendly, int chaserefs )
{
	LDAP	*ld = NULL;
	int  	i, do_retry = maxretries;
	char	*DNs[2];
	char	*rdns[2];
	int	rc = LDAP_SUCCESS;
	char	*p1, *p2;
	int	version = LDAP_VERSION3;

	DNs[0] = entry;
	DNs[1] = strdup( entry );

	/* reverse the RDN, make new DN */
	p1 = strchr( entry, '=' ) + 1;
	p2 = strchr( p1, ',' );

	*p2 = '\0';
	rdns[1] = strdup( entry );
	*p2-- = ',';

	for (i = p1 - entry;p2 >= p1;)
		DNs[1][i++] = *p2--;
	
	DNs[1][i] = '\0';
	rdns[0] = strdup( DNs[1] );
	DNs[1][i] = ',';

	i = 0;

retry:;
	ldap_initialize( &ld, uri );
	if ( ld == NULL ) {
		tester_perror( "ldap_initialize", NULL );
		exit( EXIT_FAILURE );
	}

	(void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version ); 
	(void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
		chaserefs ? LDAP_OPT_ON : LDAP_OPT_OFF );

	if ( do_retry == maxretries ) {
		fprintf( stderr, "PID=%ld - Modrdn(%d): entry=\"%s\".\n",
			(long) pid, maxloop, entry );
	}

	rc = ldap_sasl_bind_s( ld, manager, LDAP_SASL_SIMPLE, passwd, NULL, NULL, NULL );
	if ( rc != LDAP_SUCCESS ) {
		tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
		switch ( rc ) {
		case LDAP_BUSY:
		case LDAP_UNAVAILABLE:
			if ( do_retry > 0 ) {
				do_retry--;
				if ( delay > 0) {
				    sleep( delay );
				}
				goto retry;
			}
		/* fallthru */
		default:
			break;
		}
		exit( EXIT_FAILURE );
	}

	for ( ; i < maxloop; i++ ) {
		rc = ldap_rename_s( ld, DNs[0], rdns[0], NULL, 0, NULL, NULL );
		if ( rc != LDAP_SUCCESS ) {
			tester_ldap_error( ld, "ldap_rename_s", NULL );
			switch ( rc ) {
			case LDAP_NO_SUCH_OBJECT:
				/* NOTE: this likely means
				 * the second modrdn failed
				 * during the previous round... */
				if ( !friendly ) {
					goto done;
				}
				break;

			case LDAP_BUSY:
			case LDAP_UNAVAILABLE:
				if ( do_retry > 0 ) {
					do_retry--;
					goto retry;
				}
				/* fall thru */

			default:
				goto done;
			}
		}
		rc = ldap_rename_s( ld, DNs[1], rdns[1], NULL, 1, NULL, NULL );
		if ( rc != LDAP_SUCCESS ) {
			tester_ldap_error( ld, "ldap_rename_s", NULL );
			switch ( rc ) {
			case LDAP_NO_SUCH_OBJECT:
				/* NOTE: this likely means
				 * the first modrdn failed
				 * during the previous round... */
				if ( !friendly ) {
					goto done;
				}
				break;

			case LDAP_BUSY:
			case LDAP_UNAVAILABLE:
				if ( do_retry > 0 ) {
					do_retry--;
					goto retry;
				}
				/* fall thru */

			default:
				goto done;
			}
		}
	}

done:;
	fprintf( stderr, "  PID=%ld - Modrdn done (%d).\n", (long) pid, rc );

	ldap_unbind_ext( ld, NULL, NULL );

	free( DNs[1] );
	free( rdns[0] );
	free( rdns[1] );
}
Example #11
0
int
ldap_unbind_ext_s(LDAP *ld, LDAPControl **sctrls, LDAPControl **cctrls)
{
    return ldap_unbind_ext(ld, sctrls, cctrls);
}
Example #12
0
/* If we only have a bindpw then try to join in a bit of a degraded mode.
 * This is going to duplicate some of the server-side code to determine
 * the state of the entry.
 */
static int
join_ldap(const char *ipaserver, char *hostname, char ** binddn, const char *bindpw, const char *basedn, const char **princ, const char **subject, int quiet)
{
    LDAP *ld;
    char *filter = NULL;
    int rval = 0;
    char *oidresult = NULL;
    struct berval valrequest;
    struct berval *valresult = NULL;
    int rc, ret;
    char *ldap_base = NULL;
    char *search_base = NULL;

    *binddn = NULL;
    *princ = NULL;
    *subject = NULL;

    if (NULL != basedn) {
        ldap_base = strdup(basedn);
        if (!ldap_base) {
            if (!quiet)
                fprintf(stderr, _("Out of memory!\n"));
            rval = 3;
            goto done;
        }
    } else {
        if (get_root_dn(ipaserver, &ldap_base) != 0) {
            if (!quiet)
                fprintf(stderr, _("Unable to determine root DN of %s\n"),
                                ipaserver);
            rval = 14;
            goto done;
        }
    }

    ret = asprintf(binddn, "fqdn=%s,cn=computers,cn=accounts,%s", hostname, ldap_base);
    if (ret == -1)
    {
        if (!quiet)
            fprintf(stderr, _("Out of memory!\n"));
        rval = 3;
        goto done;
    }
    ld = connect_ldap(ipaserver, *binddn, bindpw);
    if (!ld) {
        if (!quiet)
            fprintf(stderr, _("Incorrect password.\n"));
        rval = 15;
        goto done;
    }

    if (get_subject(ld, ldap_base, subject, quiet) != 0) {
        if (!quiet)
            fprintf(stderr,
                    _("Unable to determine certificate subject of %s\n"),
                    ipaserver);
        /* Not a critical failure */
    }

    valrequest.bv_val = (char *)hostname;
    valrequest.bv_len = strlen(hostname);

    if ((rc = ldap_extended_operation_s(ld, JOIN_OID, &valrequest, NULL, NULL, &oidresult, &valresult)) != LDAP_SUCCESS) {
        char *s = NULL;
#ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE
        ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, &s);
#else
        ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &s);
#endif
        if (!quiet)
            fprintf(stderr, _("Enrollment failed. %s\n"), s);
        if (debug) {
            fprintf(stderr, "ldap_extended_operation_s failed: %s",
                            ldap_err2string(rc));
        }
        rval = 13;
        goto ldap_done;
    }

    /* Get the value from the result returned by the server. */
    *princ = strdup(valresult->bv_val);

ldap_done:

    free(filter);
    free(search_base);
    free(ldap_base);

    if (ld != NULL) {
        ldap_unbind_ext(ld, NULL, NULL);
    }

done:
    if (valresult) ber_bvfree(valresult);
    if (oidresult) free(oidresult);
    return rval;
}
Example #13
0
/*
 * Determine the baseDN of the remote server. Look first for a
 * defaultNamingContext, otherwise fall back to reviewing each
 * namingContext.
 */
static int
get_root_dn(const char *ipaserver, char **ldap_base)
{
    LDAP *ld = NULL;
    char *root_attrs[] = {"namingContexts", "defaultNamingContext", NULL};
    LDAPMessage *entry, *res = NULL;
    struct berval **ncvals;
    struct berval **defvals;
    int ret, rval = 0;

    ld = connect_ldap(ipaserver, NULL, NULL);
    if (!ld) {
        rval = 14;
        goto done;
    }

    ret = ldap_search_ext_s(ld, "", LDAP_SCOPE_BASE,
                            "objectclass=*", root_attrs, 0,
                            NULL, NULL, NULL, 0, &res);

    if (ret != LDAP_SUCCESS) {
        fprintf(stderr, _("Search for %1$s on rootdse failed with error %2$d\n"),
                root_attrs[0], ret);
        rval = 14;
        goto done;
    }

   *ldap_base = NULL;

    entry = ldap_first_entry(ld, res);

    defvals = ldap_get_values_len(ld, entry, root_attrs[1]);
    if (defvals) {
        ret = check_ipa_server(ld, ldap_base, defvals);
    }
    ldap_value_free_len(defvals);

    /* loop through to find the IPA context */
    if (ret == LDAP_SUCCESS &&  !*ldap_base) {
        ncvals = ldap_get_values_len(ld, entry, root_attrs[0]);
        if (!ncvals) {
            fprintf(stderr, _("No values for %s"), root_attrs[0]);
            rval = 14;
            ldap_value_free_len(ncvals);
            goto done;
        }
        ret = check_ipa_server(ld, ldap_base, ncvals);
        ldap_value_free_len(ncvals);
    }

    if (ret != LDAP_SUCCESS) {
        fprintf(stderr, _("Search for IPA namingContext failed with error %d\n"), ret);
        rval = 14;
        goto done;
    }

    if (!*ldap_base) {
        fprintf(stderr, _("IPA namingContext not found\n"));
        rval = 14;
        goto done;
    }


done:
    if (res) ldap_msgfree(res);
    if (ld != NULL) {
        ldap_unbind_ext(ld, NULL, NULL);
    }

    return rval;
}
static void
do_addel(
    char *uri,
    char *manager,
    struct berval *passwd,
    char *entry,
    LDAPMod **attrs,
    int maxloop,
    int maxretries,
    int delay,
    int friendly,
    int chaserefs )
{
    LDAP	*ld = NULL;
    int  	i = 0, do_retry = maxretries;
    int	rc = LDAP_SUCCESS;
    int	version = LDAP_VERSION3;

retry:
    ;
    ldap_initialize( &ld, uri );
    if ( ld == NULL ) {
        tester_perror( "ldap_initialize", NULL );
        exit( EXIT_FAILURE );
    }

    (void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version );
    (void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
                            chaserefs ? LDAP_OPT_ON : LDAP_OPT_OFF );

    if ( do_retry == maxretries ) {
        fprintf( stderr, "PID=%ld - Add/Delete(%d): entry=\"%s\".\n",
                 (long) pid, maxloop, entry );
    }

    rc = ldap_sasl_bind_s( ld, manager, LDAP_SASL_SIMPLE, passwd, NULL, NULL, NULL );
    if ( rc != LDAP_SUCCESS ) {
        tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
        switch ( rc ) {
        case LDAP_BUSY:
        case LDAP_UNAVAILABLE:
            if ( do_retry > 0 ) {
                do_retry--;
                if ( delay != 0 ) {
                    sleep( delay );
                }
                goto retry;
            }
        /* fallthru */
        default:
            break;
        }
        exit( EXIT_FAILURE );
    }

    for ( ; i < maxloop; i++ ) {

        /* add the entry */
        rc = ldap_add_ext_s( ld, entry, attrs, NULL, NULL );
        if ( rc != LDAP_SUCCESS ) {
            tester_ldap_error( ld, "ldap_add_ext_s", NULL );
            switch ( rc ) {
            case LDAP_ALREADY_EXISTS:
                /* NOTE: this likely means
                 * the delete failed
                 * during the previous round... */
                if ( !friendly ) {
                    goto done;
                }
                break;

            case LDAP_BUSY:
            case LDAP_UNAVAILABLE:
                if ( do_retry > 0 ) {
                    do_retry--;
                    goto retry;
                }
            /* fall thru */

            default:
                goto done;
            }
        }

#if 0
        /* wait a second for the add to really complete */
        /* This masks some race conditions though. */
        sleep( 1 );
#endif

        /* now delete the entry again */
        rc = ldap_delete_ext_s( ld, entry, NULL, NULL );
        if ( rc != LDAP_SUCCESS ) {
            tester_ldap_error( ld, "ldap_delete_ext_s", NULL );
            switch ( rc ) {
            case LDAP_NO_SUCH_OBJECT:
                /* NOTE: this likely means
                 * the add failed
                 * during the previous round... */
                if ( !friendly ) {
                    goto done;
                }
                break;

            case LDAP_BUSY:
            case LDAP_UNAVAILABLE:
                if ( do_retry > 0 ) {
                    do_retry--;
                    goto retry;
                }
            /* fall thru */

            default:
                goto done;
            }
        }
    }

done:
    ;
    fprintf( stderr, " PID=%ld - Add/Delete done (%d).\n", (long) pid, rc );

    ldap_unbind_ext( ld, NULL, NULL );
}
Example #15
0
static int ldap_set_keytab(krb5_context krbctx,
			   const char *servername,
			   const char *principal_name,
			   krb5_principal princ,
			   const char *binddn,
			   const char *bindpw,
			   struct keys_container *keys)
{
	LDAP *ld = NULL;
	BerElement *sctrl = NULL;
	struct berval *control = NULL;
	LDAPControl **srvctrl = NULL;
	int ret;
	int kvno, i;
	ber_tag_t rtag;
	ber_int_t *encs = NULL;
	int successful_keys = 0;

	/* cant' return more than nkeys, sometimes less */
	encs = calloc(keys->nkeys + 1, sizeof(ber_int_t));
	if (!encs) {
		fprintf(stderr, _("Out of Memory!\n"));
		return 0;
	}

	/* build password change control */
	control = create_key_control(keys, principal_name);
	if (!control) {
		fprintf(stderr, _("Failed to create control!\n"));
		goto error_out;
	}

    ret = ipa_ldap_bind(servername, princ, binddn, bindpw, &ld);
    if (ret != LDAP_SUCCESS) {
        fprintf(stderr, _("Failed to bind to server!\n"));
        goto error_out;
    }

    /* perform password change */
    ret = ipa_ldap_extended_op(ld, KEYTAB_SET_OID, control, &srvctrl);
    if (ret != LDAP_SUCCESS) {
        fprintf(stderr, _("Failed to get keytab!\n"));
        goto error_out;
    }

	ber_bvfree(control);
	control = NULL;

	sctrl = get_control_data(srvctrl, KEYTAB_RET_OID);
	if (!sctrl) {
		fprintf(stderr, _("ber_init() failed, Invalid control ?!\n"));
		goto error_out;
	}

	/* Format of response
	 *
	 * KeytabGetRequest ::= SEQUENCE {
	 * 	new_kvno	Int32
	 * 	SEQUENCE OF	KeyTypes
	 * }
	 *
	 * * List of accepted enctypes *
	 * KeyTypes ::= SEQUENCE {
	 * 	enctype		Int32
	 * }
	 */

	rtag = ber_scanf(sctrl, "{i{", &kvno);
	if (rtag == LBER_ERROR) {
		fprintf(stderr, _("ber_scanf() failed, unable to find kvno ?!\n"));
		goto error_out;
	}

	for (i = 0; i < keys->nkeys; i++) {
		ret = ber_scanf(sctrl, "{i}", &encs[i]);
		if (ret == LBER_ERROR) {
			char enc[79]; /* fit std terminal or truncate */
			krb5_error_code krberr;
			krberr = krb5_enctype_to_string(
				keys->ksdata[i].enctype, enc, 79);
			if (krberr) {
				fprintf(stderr, _("Failed to retrieve "
					"encryption type type #%d\n"),
					keys->ksdata[i].enctype);
			} else {
				fprintf(stderr, _("Failed to retrieve "
					"encryption type %1$s (#%2$d)\n"),
					enc, keys->ksdata[i].enctype);
			}
                } else {
			successful_keys++;
		}
	}

	if (successful_keys == 0) {
		fprintf(stderr, _("Failed to retrieve any keys"));
		goto error_out;
	}

	ret = filter_keys(krbctx, keys, encs);
	if (ret == 0) goto error_out;

	ber_free(sctrl, 1);
	ldap_controls_free(srvctrl);
	ldap_unbind_ext(ld, NULL, NULL);
	free(encs);
	return kvno;

error_out:
	if (sctrl) ber_free(sctrl, 1);
	if (srvctrl) ldap_controls_free(srvctrl);
	if (ld) ldap_unbind_ext(ld, NULL, NULL);
	if (control) ber_bvfree(control);
	free(encs);
	return -1;
}
Example #16
0
static void
do_modify( char *uri, char *manager,
	struct berval *passwd, char *entry, char* attr, char* value,
	int maxloop, int maxretries, int delay, int friendly, int chaserefs )
{
	LDAP	*ld = NULL;
	int  	i = 0, do_retry = maxretries;
	int     rc = LDAP_SUCCESS;

	struct ldapmod mod;
	struct ldapmod *mods[2];
	char *values[2];
	int version = LDAP_VERSION3;

	values[0] = value;
	values[1] = NULL;
	mod.mod_op = LDAP_MOD_ADD;
	mod.mod_type = attr;
	mod.mod_values = values;
	mods[0] = &mod;
	mods[1] = NULL;

retry:;
	ldap_initialize( &ld, uri );
	if ( ld == NULL ) {
		tester_perror( "ldap_initialize", NULL );
		exit( EXIT_FAILURE );
	}

	(void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version ); 
	(void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
		chaserefs ? LDAP_OPT_ON : LDAP_OPT_OFF );

	if ( do_retry == maxretries ) {
		fprintf( stderr, "PID=%ld - Modify(%d): entry=\"%s\".\n",
			(long) pid, maxloop, entry );
	}

	rc = ldap_sasl_bind_s( ld, manager, LDAP_SASL_SIMPLE, passwd, NULL, NULL, NULL );
	if ( rc != LDAP_SUCCESS ) {
		tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
		switch ( rc ) {
		case LDAP_BUSY:
		case LDAP_UNAVAILABLE:
			if ( do_retry > 0 ) {
				do_retry--;
				if ( delay > 0 ) {
				    sleep( delay );
				}
				goto retry;
			}
		/* fallthru */
		default:
			break;
		}
		exit( EXIT_FAILURE );
	}

	for ( ; i < maxloop; i++ ) {
		mod.mod_op = LDAP_MOD_ADD;
		rc = ldap_modify_ext_s( ld, entry, mods, NULL, NULL );
		if ( rc != LDAP_SUCCESS ) {
			tester_ldap_error( ld, "ldap_modify_ext_s", NULL );
			switch ( rc ) {
			case LDAP_TYPE_OR_VALUE_EXISTS:
				/* NOTE: this likely means
				 * the second modify failed
				 * during the previous round... */
				if ( !friendly ) {
					goto done;
				}
				break;

			case LDAP_BUSY:
			case LDAP_UNAVAILABLE:
				if ( do_retry > 0 ) {
					do_retry--;
					goto retry;
				}
				/* fall thru */

			default:
				goto done;
			}
		}
		
		mod.mod_op = LDAP_MOD_DELETE;
		rc = ldap_modify_ext_s( ld, entry, mods, NULL, NULL );
		if ( rc != LDAP_SUCCESS ) {
			tester_ldap_error( ld, "ldap_modify_ext_s", NULL );
			switch ( rc ) {
			case LDAP_NO_SUCH_ATTRIBUTE:
				/* NOTE: this likely means
				 * the first modify failed
				 * during the previous round... */
				if ( !friendly ) {
					goto done;
				}
				break;

			case LDAP_BUSY:
			case LDAP_UNAVAILABLE:
				if ( do_retry > 0 ) {
					do_retry--;
					goto retry;
				}
				/* fall thru */

			default:
				goto done;
			}
		}

	}

done:;
	fprintf( stderr, "  PID=%ld - Modify done (%d).\n", (long) pid, rc );

	ldap_unbind_ext( ld, NULL, NULL );
}
Example #17
0
static int ldap_get_keytab(krb5_context krbctx, bool generate, char *password,
                           const char *enctypes, const char *bind_server,
                           const char *svc_princ, krb5_principal bind_princ,
                           const char *bind_dn, const char *bind_pw,
                           struct keys_container *keys, int *kvno,
                           char **err_msg)
{
    struct krb_key_salt *es = NULL;
    int num_es = 0;
    struct berval *control = NULL;
    LDAP *ld = NULL;
    LDAPControl **srvctrl = NULL;
    struct berval data;
    bool res;
    int ret;

    *err_msg = NULL;

    if (enctypes) {
        ret = ipa_string_to_enctypes(enctypes, &es, &num_es, err_msg);
        if (ret || num_es == 0) {
            return LDAP_OPERATIONS_ERROR;
        }
    }

    control = create_getkeytab_control(svc_princ, generate,
                                       password, es, num_es);
    if (!control) {
        *err_msg = _("Failed to create control!\n");
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    ret = ipa_ldap_bind(bind_server, bind_princ, bind_dn, bind_pw, &ld);
    if (ret != LDAP_SUCCESS) {
        *err_msg = _("Failed to bind to server!\n");
        goto done;
    }

    /* perform extedned opt to get keytab */
    ret = ipa_ldap_extended_op(ld, KEYTAB_GET_OID, control, &srvctrl);
    if (ret != LDAP_SUCCESS) {
        goto done;
    }

    ret = find_control_data(srvctrl, KEYTAB_GET_OID, &data);
    if (ret != LDAP_SUCCESS) goto done;

    res = ipaasn1_dec_getktreply(data.bv_val, data.bv_len, kvno, keys);
    if (!res) {
        *err_msg = _("Failed to decode control reply!\n");
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    ret = LDAP_SUCCESS;

done:
    if (ld) ldap_unbind_ext(ld, NULL, NULL);
    if (control) ber_bvfree(control);
    free(es);
    if (ret) {
        free_keys_contents(krbctx, keys);
    }
    return ret;
}
Example #18
0
static void
do_read( char *uri, char *manager, struct berval *passwd, char *entry,
	LDAP **ldp, char **attrs, int noattrs, int nobind, int maxloop,
	int maxretries, int delay, int force, int chaserefs )
{
	LDAP	*ld = ldp ? *ldp : NULL;
	int  	i = 0, do_retry = maxretries;
	int     rc = LDAP_SUCCESS;
	int	version = LDAP_VERSION3;

retry:;
	if ( ld == NULL ) {
		ldap_initialize( &ld, uri );
		if ( ld == NULL ) {
			tester_perror( "ldap_initialize", NULL );
			exit( EXIT_FAILURE );
		}

		(void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version );
		(void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
			chaserefs ? LDAP_OPT_ON : LDAP_OPT_OFF );

		if ( do_retry == maxretries ) {
			fprintf( stderr, "PID=%ld - Read(%d): entry=\"%s\".\n",
				(long) pid, maxloop, entry );
		}

		if ( nobind == 0 ) {
			rc = ldap_sasl_bind_s( ld, manager, LDAP_SASL_SIMPLE, passwd, NULL, NULL, NULL );
			if ( rc != LDAP_SUCCESS ) {
				tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
				switch ( rc ) {
				case LDAP_BUSY:
				case LDAP_UNAVAILABLE:
					if ( do_retry > 0 ) {
						ldap_unbind_ext( ld, NULL, NULL );
						ld = NULL;
						do_retry--;
						if ( delay != 0 ) {
						    sleep( delay );
						}
						goto retry;
					}
				/* fallthru */
				default:
					break;
				}
				exit( EXIT_FAILURE );
			}
		}
	}

	for ( ; i < maxloop; i++ ) {
		LDAPMessage *res = NULL;

		rc = ldap_search_ext_s( ld, entry, LDAP_SCOPE_BASE,
				NULL, attrs, noattrs, NULL, NULL, NULL,
				LDAP_NO_LIMIT, &res );
		if ( res != NULL ) {
			ldap_msgfree( res );
		}

		if ( rc ) {
			int		first = tester_ignore_err( rc );
			char		buf[ BUFSIZ ];

			snprintf( buf, sizeof( buf ), "ldap_search_ext_s(%s)", entry );

			/* if ignore.. */
			if ( first ) {
				/* only log if first occurrence */
				if ( ( force < 2 && first > 0 ) || abs(first) == 1 ) {
					tester_ldap_error( ld, buf, NULL );
				}
				continue;
			}

			/* busy needs special handling */
			tester_ldap_error( ld, buf, NULL );
			if ( rc == LDAP_BUSY && do_retry > 0 ) {
				ldap_unbind_ext( ld, NULL, NULL );
				ld = NULL;
				do_retry--;
				goto retry;
			}
			break;
		}
	}

	if ( ldp != NULL ) {
		*ldp = ld;

	} else {
		fprintf( stderr, "  PID=%ld - Read done (%d).\n", (long) pid, rc );

		if ( ld != NULL ) {
			ldap_unbind_ext( ld, NULL, NULL );
		}
	}
}
Example #19
0
static int l_search_do_filter(struct ldapsearch *s,
			      int (*callback_func)(const char *utf8_name,
						   const char *address,
						   void *callback_arg),
			      void *callback_arg,
			      const char *filter,
			      const char *lookup_key,
			      int *found)
{
	char *kk;
	struct timeval tv;
	LDAPMessage *result;
	char *attrs[3];
	int rc_code=0;
	int msgidp;

	*found=0;

	kk=make_search_key(filter, lookup_key);

	if (!kk)
		return -1;

	if (s->handle == NULL)
	{
		errno=ETIMEDOUT;  /* Timeout previously */
		return -1;
	}


	attrs[0]="cn";
	attrs[1]="mail";
	attrs[2]=NULL;

	tv.tv_sec=60*60;
	tv.tv_usec=0;

	if (ldap_search_ext(s->handle, s->base, LDAP_SCOPE_SUBTREE,
			    kk, attrs, 0, NULL, NULL, &tv, 1000000, &msgidp)
	    != LDAP_SUCCESS)
		return -1;

	do
	{
		int rc;
		LDAPMessage *msg;

		const char *timeout=getenv("LDAP_SEARCH_TIMEOUT");

		tv.tv_sec=atoi(timeout ? timeout:"30");
		tv.tv_usec=0;

		rc=ldap_result(s->handle, msgidp, 0, &tv, &result);

		if (rc <= 0)
		{
			if (rc == 0)
				errno=ETIMEDOUT;

			ldap_unbind_ext(s->handle, NULL, NULL);
			s->handle=NULL;
			rc_code= -1;
			break;
		}

		if (rc == LDAP_RES_SEARCH_RESULT)
		{
			ldap_msgfree(result);
			break; /* End of search */
		}

		if (rc != LDAP_RES_SEARCH_ENTRY)
		{
			ldap_msgfree(result);
			continue;
		}

		for (msg=ldap_first_message(s->handle, result); msg;
		     msg=ldap_next_message(s->handle, msg))
		{
			struct berval **n_val=
				ldap_get_values_len(s->handle, msg, "cn");
			struct berval **a_val=
				ldap_get_values_len(s->handle, msg, "mail");

			if (n_val && a_val)
			{
				size_t i, j;

				for (i=0; n_val[i]; i++)
					for (j=0; a_val[j]; j++)
					{
						char *p=malloc(n_val[i]->bv_len
							       +1);
						char *q=malloc(a_val[j]->bv_len
							       +1);

						if (!p || !q)
						{
							if (p) free(p);
							if (q) free(q);
							rc_code= -1;
							break;
						}

						memcpy(p, n_val[i]->bv_val,
						       n_val[i]->bv_len);
						p[n_val[i]->bv_len]=0;

						memcpy(q, a_val[j]->bv_val,
						       a_val[j]->bv_len);
						q[a_val[j]->bv_len]=0;

						rc_code=(*callback_func)
							(p, q, callback_arg);
						free(p);
						free(q);
						if (rc_code)
							break;
						*found=1;
					}
			}
			if (n_val)
				ldap_value_free_len(n_val);
			if (a_val)
				ldap_value_free_len(a_val);
		}

		ldap_msgfree(result);
	} while (rc_code == 0);
	return rc_code;
}
Example #20
0
static void
do_read( char *uri, char *manager, struct berval *passwd, char *entry,
	LDAP **ldp, char **attrs, int noattrs, int nobind, int maxloop,
	int maxretries, int delay, int force, int chaserefs )
{
	LDAP	*ld = ldp ? *ldp : NULL;
	int  	i = 0, do_retry = maxretries;
	int     rc = LDAP_SUCCESS;
	int		version = LDAP_VERSION3;
	int		*msgids = NULL, active = 0;

	/* make room for msgid */
	if ( swamp > 1 ) {
		msgids = (int *)calloc( sizeof(int), maxloop );
	}

retry:;
	if ( ld == NULL ) {
		ldap_initialize( &ld, uri );
		if ( ld == NULL ) {
			tester_perror( "ldap_initialize", NULL );
			exit( EXIT_FAILURE );
		}

		(void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version ); 
		(void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
			chaserefs ? LDAP_OPT_ON : LDAP_OPT_OFF );

		if ( do_retry == maxretries ) {
			fprintf( stderr, "PID=%ld - Read(%d): entry=\"%s\".\n",
				(long) pid, maxloop, entry );
		}

		if ( nobind == 0 ) {
			rc = ldap_sasl_bind_s( ld, manager, LDAP_SASL_SIMPLE, passwd, NULL, NULL, NULL );
			if ( rc != LDAP_SUCCESS ) {
				tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
				switch ( rc ) {
				case LDAP_BUSY:
				case LDAP_UNAVAILABLE:
					if ( do_retry > 0 ) {
						ldap_unbind_ext( ld, NULL, NULL );
						ld = NULL;
						do_retry--;
						if ( delay != 0 ) {
						    sleep( delay );
						}
						goto retry;
					}
				/* fallthru */
				default:
					break;
				}
				exit( EXIT_FAILURE );
			}
		}
	}

	if ( swamp > 1 ) {
		do {
			LDAPMessage *res = NULL;
			int j, msgid;

			if ( i < maxloop ) {
				rc = ldap_search_ext( ld, entry, LDAP_SCOPE_BASE,
						NULL, attrs, noattrs, NULL, NULL,
						NULL, LDAP_NO_LIMIT, &msgids[i] );

				active++;
#if 0
				fprintf( stderr,
					">>> PID=%ld - Read maxloop=%d cnt=%d active=%d msgid=%d: "
					"entry=\"%s\"\n",
					(long) pid, maxloop, i, active, msgids[i],
					entry );
#endif
				i++;

				if ( rc ) {
					char buf[BUFSIZ];
					int first = tester_ignore_err( rc );
					/* if ignore.. */
					if ( first ) {
						/* only log if first occurrence */
						if ( ( force < 2 && first > 0 ) || abs(first) == 1 ) {
							tester_ldap_error( ld, "ldap_search_ext", NULL );
						}
						continue;
					}
		
					/* busy needs special handling */
					snprintf( buf, sizeof( buf ), "entry=\"%s\"\n", entry );
					tester_ldap_error( ld, "ldap_search_ext", buf );
					if ( rc == LDAP_BUSY && do_retry > 0 ) {
						ldap_unbind_ext( ld, NULL, NULL );
						ld = NULL;
						do_retry--;
						goto retry;
					}
					break;
				}

				if ( swamp > 2 ) {
					continue;
				}
			}

			rc = ldap_result( ld, LDAP_RES_ANY, 0, NULL, &res );
			switch ( rc ) {
			case -1:
				/* gone really bad */
#if 0
				fprintf( stderr,
					">>> PID=%ld - Read maxloop=%d cnt=%d active=%d: "
					"entry=\"%s\" ldap_result()=%d\n",
					(long) pid, maxloop, i, active, entry, rc );
#endif
				goto cleanup;
	
			case 0:
				/* timeout (impossible) */
				break;
	
			case LDAP_RES_SEARCH_ENTRY:
			case LDAP_RES_SEARCH_REFERENCE:
				/* ignore */
				break;
	
			case LDAP_RES_SEARCH_RESULT:
				/* just remove, no error checking (TODO?) */
				msgid = ldap_msgid( res );
				ldap_parse_result( ld, res, &rc, NULL, NULL, NULL, NULL, 1 );
				res = NULL;

				/* linear search, bah */
				for ( j = 0; j < i; j++ ) {
					if ( msgids[ j ] == msgid ) {
						msgids[ j ] = -1;
						active--;
#if 0
						fprintf( stderr,
							"<<< PID=%ld - ReadDone maxloop=%d cnt=%d active=%d msgid=%d: "
							"entry=\"%s\"\n",
							(long) pid, maxloop, j, active, msgid, entry );
#endif
						break;
					}
				}
				break;

			default:
				/* other messages unexpected */
				fprintf( stderr,
					"### PID=%ld - Read(%d): "
					"entry=\"%s\" attrs=%s%s. unexpected response tag=%d\n",
					(long) pid, maxloop,
					entry, attrs[0], attrs[1] ? " (more...)" : "", rc );
				break;
			}

			if ( res != NULL ) {
				ldap_msgfree( res );
			}
		} while ( i < maxloop || active > 0 );

	} else {
		for ( ; i < maxloop; i++ ) {
			LDAPMessage *res = NULL;

			if (swamp) {
				int msgid;
				rc = ldap_search_ext( ld, entry, LDAP_SCOPE_BASE,
						NULL, attrs, noattrs, NULL, NULL,
						NULL, LDAP_NO_LIMIT, &msgid );
				if ( rc == LDAP_SUCCESS ) continue;
				else break;
			}
	
			rc = ldap_search_ext_s( ld, entry, LDAP_SCOPE_BASE,
					NULL, attrs, noattrs, NULL, NULL, NULL,
					LDAP_NO_LIMIT, &res );
			if ( res != NULL ) {
				ldap_msgfree( res );
			}

			if ( rc ) {
				int		first = tester_ignore_err( rc );
				char		buf[ BUFSIZ ];
	
				snprintf( buf, sizeof( buf ), "ldap_search_ext_s(%s)", entry );
	
				/* if ignore.. */
				if ( first ) {
					/* only log if first occurrence */
					if ( ( force < 2 && first > 0 ) || abs(first) == 1 ) {
						tester_ldap_error( ld, buf, NULL );
					}
					continue;
				}
	
				/* busy needs special handling */
				tester_ldap_error( ld, buf, NULL );
				if ( rc == LDAP_BUSY && do_retry > 0 ) {
					ldap_unbind_ext( ld, NULL, NULL );
					ld = NULL;
					do_retry--;
					goto retry;
				}
				break;
			}
		}
	}

cleanup:;
	if ( msgids != NULL ) {
		free( msgids );
	}

	if ( ldp != NULL ) {
		*ldp = ld;

	} else {
		fprintf( stderr, "  PID=%ld - Read done (%d).\n", (long) pid, rc );

		if ( ld != NULL ) {
			ldap_unbind_ext( ld, NULL, NULL );
		}
	}
}
Example #21
0
static int
do_bind( char *uri, char *dn, struct berval *pass, int maxloop,
	int force, int chaserefs, int noinit, LDAP **ldp,
	int action_type, void *action )
{
	LDAP	*ld = ldp ? *ldp : NULL;
	int  	i, rc = -1;

	/* for internal search */
	int	timelimit = 0;
	int	sizelimit = 0;

	switch ( action_type ) {
	case -1:
		break;

	case TESTER_SEARCH:
		{
		LDAPURLDesc	*ludp = (LDAPURLDesc *)action;

		assert( action != NULL );

		if ( ludp->lud_exts != NULL ) {
			for ( i = 0; ludp->lud_exts[ i ] != NULL; i++ ) {
				char	*ext = ludp->lud_exts[ i ];
				int	crit = 0;

				if (ext[0] == '!') {
					crit++;
					ext++;
				}

				if ( strncasecmp( ext, "x-timelimit=", STRLENOF( "x-timelimit=" ) ) == 0 ) {
					if ( lutil_atoi( &timelimit, &ext[ STRLENOF( "x-timelimit=" ) ] ) && crit ) {
						tester_error( "unable to parse critical extension x-timelimit" );
					}

				} else if ( strncasecmp( ext, "x-sizelimit=", STRLENOF( "x-sizelimit=" ) ) == 0 ) {
					if ( lutil_atoi( &sizelimit, &ext[ STRLENOF( "x-sizelimit=" ) ] ) && crit ) {
						tester_error( "unable to parse critical extension x-sizelimit" );
					}

				} else if ( crit ) {
					tester_error( "unknown critical extension" );
				}
			}
		}
		} break;

	default:
		/* nothing to do yet */
		break;
	}
			
	if ( maxloop > 1 ) {
		fprintf( stderr, "PID=%ld - Bind(%d): dn=\"%s\".\n",
			 (long) pid, maxloop, dn );
	}

	for ( i = 0; i < maxloop; i++ ) {
		if ( !noinit || ld == NULL ) {
			int version = LDAP_VERSION3;
			ldap_initialize( &ld, uri );
			if ( ld == NULL ) {
				tester_perror( "ldap_initialize", NULL );
				rc = -1;
				break;
			}

			(void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION,
				&version ); 
			(void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
				chaserefs ? LDAP_OPT_ON: LDAP_OPT_OFF );
		}

		rc = ldap_sasl_bind_s( ld, dn, LDAP_SASL_SIMPLE, pass, NULL, NULL, NULL );
		if ( rc ) {
			int first = tester_ignore_err( rc );

			/* if ignore.. */
			if ( first ) {
				/* only log if first occurrence */
				if ( ( force < 2 && first > 0 ) || abs(first) == 1 ) {
					tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
				}
				rc = LDAP_SUCCESS;

			} else {
				tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
			}
		}

		switch ( action_type ) {
		case -1:
			break;

		case TESTER_SEARCH:
			{
			LDAPURLDesc	*ludp = (LDAPURLDesc *)action;
			LDAPMessage	*res = NULL;
			struct timeval	tv = { 0 }, *tvp = NULL;

			if ( timelimit ) {
				tv.tv_sec = timelimit;
				tvp = &tv;
			}

			assert( action != NULL );

			rc = ldap_search_ext_s( ld,
				ludp->lud_dn, ludp->lud_scope,
				ludp->lud_filter, ludp->lud_attrs, 0,
				NULL, NULL, tvp, sizelimit, &res );
			ldap_msgfree( res );
			} break;

		default:
			/* nothing to do yet */
			break;
		}
			
		if ( !noinit ) {
			ldap_unbind_ext( ld, NULL, NULL );
			ld = NULL;
		}

		if ( rc != LDAP_SUCCESS ) {
			break;
		}
	}

	if ( maxloop > 1 ) {
		fprintf( stderr, "  PID=%ld - Bind done (%d).\n", (long) pid, rc );
	}

	if ( ldp && noinit ) {
		*ldp = ld;

	} else if ( ld != NULL ) {
		ldap_unbind_ext( ld, NULL, NULL );
	}

	return rc;
}
Example #22
0
int
ldap_init_fd(
	ber_socket_t fd,
	int proto,
	LDAP_CONST char *url,
	LDAP **ldp
)
{
	int rc;
	LDAP *ld;
	LDAPConn *conn;

	*ldp = NULL;
	rc = ldap_create( &ld );
	if( rc != LDAP_SUCCESS )
		return( rc );

	if (url != NULL) {
		rc = ldap_set_option(ld, LDAP_OPT_URI, url);
		if ( rc != LDAP_SUCCESS ) {
			ldap_ld_free(ld, 1, NULL, NULL);
			return rc;
		}
	}

	LDAP_MUTEX_LOCK( &ld->ld_conn_mutex );
	/* Attach the passed socket as the LDAP's connection */
	conn = ldap_new_connection( ld, NULL, 1, 0, NULL, 0, 0 );
	if( conn == NULL ) {
		ldap_unbind_ext( ld, NULL, NULL );
		return( LDAP_NO_MEMORY );
	}
	if( url )
		conn->lconn_server = ldap_url_dup( ld->ld_options.ldo_defludp );
	ber_sockbuf_ctrl( conn->lconn_sb, LBER_SB_OPT_SET_FD, &fd );
	ld->ld_defconn = conn;
	++ld->ld_defconn->lconn_refcnt;	/* so it never gets closed/freed */
	LDAP_MUTEX_UNLOCK( &ld->ld_conn_mutex );

	switch( proto ) {
	case LDAP_PROTO_TCP:
#ifdef LDAP_DEBUG
		ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_debug,
			LBER_SBIOD_LEVEL_PROVIDER, (void *)"tcp_" );
#endif
		ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_tcp,
			LBER_SBIOD_LEVEL_PROVIDER, NULL );
		break;

#ifdef LDAP_CONNECTIONLESS
	case LDAP_PROTO_UDP:
#ifdef LDAP_DEBUG
		ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_debug,
			LBER_SBIOD_LEVEL_PROVIDER, (void *)"udp_" );
#endif
		ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_udp,
			LBER_SBIOD_LEVEL_PROVIDER, NULL );
		ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_readahead,
			LBER_SBIOD_LEVEL_PROVIDER, NULL );
		break;
#endif /* LDAP_CONNECTIONLESS */

	case LDAP_PROTO_IPC:
#ifdef LDAP_DEBUG
		ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_debug,
			LBER_SBIOD_LEVEL_PROVIDER, (void *)"ipc_" );
#endif
		ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_fd,
			LBER_SBIOD_LEVEL_PROVIDER, NULL );
		break;

	case LDAP_PROTO_EXT:
		/* caller must supply sockbuf handlers */
		break;

	default:
		ldap_unbind_ext( ld, NULL, NULL );
		return LDAP_PARAM_ERROR;
	}

#ifdef LDAP_DEBUG
	ber_sockbuf_add_io( conn->lconn_sb, &ber_sockbuf_io_debug,
		INT_MAX, (void *)"ldap_" );
#endif

	/* Add the connection to the *LDAP's select pool */
	ldap_mark_select_read( ld, conn->lconn_sb );
	
	*ldp = ld;
	return LDAP_SUCCESS;
}
Example #23
0
static int
do_base( char *uri, char *dn, struct berval *pass, char *base, char *filter, char *pwattr,
	int maxloop, int force, int chaserefs, int noinit, int delay,
	int action_type, void *action )
{
	LDAP	*ld = NULL;
	int  	i = 0;
	int     rc = LDAP_SUCCESS;
	ber_int_t msgid;
	LDAPMessage *res, *msg;
	char **dns = NULL;
	struct berval *creds = NULL;
	char *attrs[] = { LDAP_NO_ATTRS, NULL };
	int ndns = 0;
#ifdef _WIN32
	DWORD beg, end;
#else
	struct timeval beg, end;
#endif
	int version = LDAP_VERSION3;
	char *nullstr = "";

	ldap_initialize( &ld, uri );
	if ( ld == NULL ) {
		tester_perror( "ldap_initialize", NULL );
		exit( EXIT_FAILURE );
	}

	(void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version );
	(void) ldap_set_option( ld, LDAP_OPT_REFERRALS,
		chaserefs ? LDAP_OPT_ON: LDAP_OPT_OFF );

	rc = ldap_sasl_bind_s( ld, dn, LDAP_SASL_SIMPLE, pass, NULL, NULL, NULL );
	if ( rc != LDAP_SUCCESS ) {
		tester_ldap_error( ld, "ldap_sasl_bind_s", NULL );
		exit( EXIT_FAILURE );
	}

	fprintf( stderr, "PID=%ld - Bind(%d): base=\"%s\", filter=\"%s\" attr=\"%s\".\n",
			(long) pid, maxloop, base, filter, pwattr );

	if ( pwattr != NULL ) {
		attrs[ 0 ] = pwattr;
	}
	rc = ldap_search_ext( ld, base, LDAP_SCOPE_SUBTREE,
			filter, attrs, 0, NULL, NULL, 0, 0, &msgid );
	if ( rc != LDAP_SUCCESS ) {
		tester_ldap_error( ld, "ldap_search_ext", NULL );
		exit( EXIT_FAILURE );
	}

	while ( ( rc = ldap_result( ld, LDAP_RES_ANY, LDAP_MSG_ONE, NULL, &res ) ) > 0 )
	{
		BerElement *ber;
		struct berval bv;
		int done = 0;

		for ( msg = ldap_first_message( ld, res ); msg;
			msg = ldap_next_message( ld, msg ) )
		{
			switch ( ldap_msgtype( msg ) ) {
			case LDAP_RES_SEARCH_ENTRY:
				rc = ldap_get_dn_ber( ld, msg, &ber, &bv );
				dns = realloc( dns, (ndns + 1)*sizeof(char *) );
				dns[ndns] = ber_strdup( bv.bv_val );
				if ( pwattr != NULL ) {
					struct berval	**values = ldap_get_values_len( ld, msg, pwattr );

					creds = realloc( creds, (ndns + 1)*sizeof(struct berval) );
					if ( values == NULL ) {
novals:;
						creds[ndns].bv_len = 0;
						creds[ndns].bv_val = nullstr;

					} else {
						static struct berval	cleartext = BER_BVC( "{CLEARTEXT} " );
						struct berval		value = *values[ 0 ];

						if ( value.bv_val[ 0 ] == '{' ) {
							char *end = ber_bvchr( &value, '}' );

							if ( end ) {
								if ( ber_bvcmp( &value, &cleartext ) == 0 ) {
									value.bv_val += cleartext.bv_len;
									value.bv_len -= cleartext.bv_len;

								} else {
									ldap_value_free_len( values );
									goto novals;
								}
							}

						}

						ber_dupbv( &creds[ndns], &value );
						ldap_value_free_len( values );
					}
				}
				ndns++;
				ber_free( ber, 0 );
				break;

			case LDAP_RES_SEARCH_RESULT:
				done = 1;
				break;
			}
			if ( done )
				break;
		}
		ldap_msgfree( res );
		if ( done ) break;
	}

#ifdef _WIN32
	beg = GetTickCount();
#else
	gettimeofday( &beg, NULL );
#endif

	if ( ndns == 0 ) {
		tester_error( "No DNs" );
		return 1;
	}

	fprintf( stderr, "  PID=%ld - Bind base=\"%s\" filter=\"%s\" got %d values.\n",
		(long) pid, base, filter, ndns );

	/* Ok, got list of DNs, now start binding to each */
	for ( i = 0; i < maxloop; i++ ) {
		int		j;
		struct berval	cred = { 0, NULL };


#if 0	/* use high-order bits for better randomness (Numerical Recipes in "C") */
		j = rand() % ndns;
#endif
		j = ((double)ndns)*rand()/(RAND_MAX + 1.0);

		if ( creds && !BER_BVISEMPTY( &creds[j] ) ) {
			cred = creds[j];
		}

		if ( do_bind( uri, dns[j], &cred, 1, force, chaserefs, noinit, &ld,
			action_type, action ) && !force )
		{
			break;
		}

		if ( delay ) {
			sleep( delay );
		}
	}

	if ( ld != NULL ) {
		ldap_unbind_ext( ld, NULL, NULL );
		ld = NULL;
	}

#ifdef _WIN32
	end = GetTickCount();
	end -= beg;

	fprintf( stderr, "  PID=%ld - Bind done %d in %d.%03d seconds.\n",
		(long) pid, i, end / 1000, end % 1000 );
#else
	gettimeofday( &end, NULL );
	end.tv_usec -= beg.tv_usec;
	if (end.tv_usec < 0 ) {
		end.tv_usec += 1000000;
		end.tv_sec -= 1;
	}
	end.tv_sec -= beg.tv_sec;

	fprintf( stderr, "  PID=%ld - Bind done %d in %ld.%06ld seconds.\n",
		(long) pid, i, (long) end.tv_sec, (long) end.tv_usec );
#endif

	if ( dns ) {
		for ( i = 0; i < ndns; i++ ) {
			ber_memfree( dns[i] );
		}
		free( dns );
	}

	if ( creds ) {
		for ( i = 0; i < ndns; i++ ) {
			if ( creds[i].bv_val != nullstr ) {
				ber_memfree( creds[i].bv_val );
			}
		}
		free( creds );
	}

	return 0;
}
Example #24
0
gpointer
worker_gda_ldap_rebind (LdapConnectionData *cdata, GError **error)
{
	if (!cdata)
		return NULL;

	/*g_print ("Trying to reconnect...\n");*/
	LDAP *ld;
	int res;
	res = ldap_initialize (&ld, cdata->url);
	if (res != LDAP_SUCCESS) {
		g_set_error (error, GDA_CONNECTION_ERROR, GDA_CONNECTION_OPEN_ERROR,
			     "%s", ldap_err2string (res));
		return NULL;
	}

	/* set protocol version to 3 by default */
	int version = LDAP_VERSION3;
	res = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &version);
        if (res != LDAP_SUCCESS) {
		if (res == LDAP_PROTOCOL_ERROR) {
			version = LDAP_VERSION2;
			res = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &version);
		}
		if (res != LDAP_SUCCESS) {
			g_set_error (error, GDA_CONNECTION_ERROR, GDA_CONNECTION_OPEN_ERROR,
				     "%s", ldap_err2string (res));
			ldap_unbind_ext (ld, NULL, NULL);
			return NULL;
		}
        }

	/* authentication */
	struct berval cred;
	const gchar *pwd = "";
	const gchar *user = "";
	if (cdata->auth)
		pwd = gda_quark_list_find (cdata->auth, "PASSWORD");
        memset (&cred, 0, sizeof (cred));
        cred.bv_len = pwd && *pwd ? strlen (pwd) : 0;
        cred.bv_val = pwd && *pwd ? (char *) pwd : NULL;

	if (cdata->auth)
		user = gda_quark_list_find (cdata->auth, "USERNAME");
	res = ldap_sasl_bind_s (ld, user, NULL, &cred, NULL, NULL, NULL);
	if (cdata->auth)
		gda_quark_list_protect_values (cdata->auth);

	if (res != LDAP_SUCCESS) {
		g_set_error (error, GDA_CONNECTION_ERROR, GDA_CONNECTION_OPEN_ERROR,
			     "%s", ldap_err2string (res));
		ldap_unbind_ext (ld, NULL, NULL);
                return NULL;
	}

	/* time limit */
	int limit = cdata->time_limit;
	res = ldap_set_option (cdata->handle, LDAP_OPT_TIMELIMIT, &limit);
	if (res != LDAP_SUCCESS) {
		g_set_error (error, GDA_CONNECTION_ERROR, GDA_CONNECTION_OPEN_ERROR,
			     "%s", ldap_err2string (res));
		ldap_unbind_ext (ld, NULL, NULL);
                return NULL;
	}

	/* size limit */
	limit = cdata->size_limit;
	res = ldap_set_option (cdata->handle, LDAP_OPT_SIZELIMIT, &limit);
	if (res != LDAP_SUCCESS) {
		g_set_error (error, GDA_CONNECTION_ERROR, GDA_CONNECTION_OPEN_ERROR,
			     "%s", ldap_err2string (res));
		ldap_unbind_ext (ld, NULL, NULL);
                return NULL;
	}

	/* all ok */
	if (cdata->handle) {
		/* don't call ldap_unbind_ext() as it often crashed the application */
		/*ldap_unbind_ext (cdata->handle, NULL, NULL);*/
	}
	cdata->handle = ld;

	/*g_print ("Reconnected!\n");*/
	return (gpointer) 0x01;
}
Example #25
0
void Ldaplogin::ldapUnbind()
{
   // ueberpruefen ob user gebannt ist
   ldap_unbind_ext(ld, NULL, NULL);
   std::cout << "aus" << std::endl;
}
Example #26
0
File: main.c Project: B-Rich/smart
/* Open LDAP and Notifier connection.
 * @return 0 on success, 1 on error.
 */
static int do_connection(univention_ldap_parameters_t *lp)
{
	LDAPMessage *res;
	int rc;
	struct timeval timeout = {
		.tv_sec = 10,
		.tv_usec = 0,
	};

	if (univention_ldap_open(lp) != LDAP_SUCCESS)
		goto fail;
	if (notifier_client_new(NULL, lp->host, 1) != 0)
		goto fail;

	/* check if we are connected to an OpenLDAP */
	rc = ldap_search_ext_s(lp->ld, lp->base, LDAP_SCOPE_BASE, "objectClass=univentionBase",
			NULL, 0, NULL, NULL, &timeout, 0, &res);
	ldap_msgfree(res);
	switch (rc) {
		case LDAP_SUCCESS:
			return 0;
		case LDAP_NO_SUCH_OBJECT:
			univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR,
					"Failed to find \"(objectClass=univentionBase)\" on LDAP server %s:%d", lp->host, lp->port);
			break;
		default:
			univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR,
					"Failed to search for \"(objectClass=univentionBase)\" on LDAP server %s:%d with message %s", lp->host, lp->port, ldap_err2string(rc));
			break;
	}
fail:
	notifier_client_destroy(NULL);
	if (lp->ld)
		ldap_unbind_ext(lp->ld, NULL, NULL);
	lp->ld = NULL;
	return 1;
}


int main(int argc, char* argv[])
{
	univention_ldap_parameters_t	*lp;
	univention_ldap_parameters_t	*lp_local;
	char *server_role;
#ifdef WITH_KRB5
	univention_krb5_parameters_t	*kp = NULL;
	bool do_kinit = false;
#else
	void				*kp = NULL ;
#endif
	int debugging = 0;
	bool from_scratch = false;
	bool foreground = false;
	bool initialize_only = false;
	bool write_transaction_file = false;
	int				 rv;
	NotifierID			 id = -1;
#ifndef WITH_DB42
	NotifierID			 old_id = -1;
#else
	CacheMasterEntry		 master_entry;
#endif
	struct stat			 stbuf;
	char *f = NULL;

	univention_debug_init("stderr", 1, 1);

	if ((lp = univention_ldap_new()) == NULL)
		exit(1);
	lp->authmethod = LDAP_AUTH_SASL;

	if ((lp_local = univention_ldap_new()) == NULL)
		exit(1);

#if WITH_KRB5
	if ((kp=univention_krb5_new()) == NULL)
		exit(1);
#endif

	/* parse arguments */
	for (;;) {
		int c;

		c = getopt(argc, argv, "d:FH:h:p:b:D:w:y:xZY:U:R:Km:Bc:giol:");
		if (c < 0)
			break;
		switch (c) {
		case 'd':
			debugging=atoi(optarg);
			break;
		case 'F':
			foreground = true;
			break;
		case 'H':
			lp->uri=strdup(optarg);
			break;
		case 'h':
			lp->host=strdup(optarg);
			break;
		case 'p':
			lp->port=atoi(optarg);
			break;
		case 'b':
			lp->base=strdup(optarg);
			break;
		case 'm':
			if ((module_dirs = realloc(module_dirs, (module_dir_count+2)*sizeof(char*))) == NULL) {
				return 1;
			}
			module_dirs[module_dir_count] = strdup(optarg);
			module_dirs[module_dir_count+1] = NULL;
			module_dir_count++;
			break;
		case 'c':
			cache_dir=strdup(optarg);
			break;
		case 'l':
			ldap_dir = strdup(optarg);
			if (asprintf(&transaction_file, "%s/listener/listener", ldap_dir) < 0) abort();
			break;
		case 'D':
			lp->binddn=strdup(optarg);
			break;
		case 'w':
			lp->bindpw=strdup(optarg);
#ifdef WITH_KRB5
			kp->password=strdup(optarg);
#endif
			/* remove password from process list */
			memset(optarg, 'X', strlen(optarg));
			break;
		case 'Z':
			lp->start_tls++;
			break;
		case 'x':
			lp->authmethod = LDAP_AUTH_SIMPLE;
			break;
		case 'y':
			lp->bindpw=read_pwd_from_file(optarg);
#ifdef WITH_KRB5
			kp->password=strdup(lp->bindpw);
#endif
			break;
		case 'Y':
			lp->sasl_mech=strdup(optarg);
			break;
		case 'U':
			asprintf(&lp->sasl_authzid, "u:%s", optarg);
			/* kp->username=strdup(optarg); */
		case 'R':
			lp->sasl_realm=strdup(optarg);
#ifdef WITH_KRB5
			kp->realm=strdup(optarg);
#endif
			break;
#ifdef WITH_KRB5
		case 'K':
			do_kinit = true;
			break;
#endif
		case 'g':
			from_scratch = true;
			break;
		case 'i':
			initialize_only = true;
			from_scratch = true;
			foreground = true;
			break;
		case 'o':
			write_transaction_file = true;
			break;
		case 'B':
			backup_notifier = 1;
			break;
		default:
			usage();
			exit(1);
		}
	}

	if (asprintf(&f, "%s/bad_cache", cache_dir) < 0) abort();
	if (stat(f, &stbuf) == 0) {
		exit(3);
	}
	free(f);

	univention_debug_set_level(UV_DEBUG_LISTENER, debugging);
	univention_debug_set_level(UV_DEBUG_LDAP, debugging);
	univention_debug_set_level(UV_DEBUG_KERBEROS, debugging);

	snprintf(pidfile, PATH_MAX, "%s/pid", cache_dir);
	signals_init();

	if (!foreground && daemonize() != 0)
		exit(EXIT_FAILURE);

	drop_privileges();

	if (from_scratch)
		purge_cache(cache_dir);

	prepare_cache(cache_dir);

	/* choose server to connect to */
	if (lp->host == NULL && lp->uri == NULL) {
		select_server(lp);
		univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_INFO,
				"no server given, choosing one by myself (%s)",
				lp->host);
	}

#ifdef WITH_KRB5
	if (!do_kinit)
		kp = NULL;
	if (kp != NULL && univention_krb5_init(kp) != 0) {
		univention_debug(UV_DEBUG_KERBEROS, UV_DEBUG_ERROR, "kinit failed");
		exit(1);
	}
#endif

	while (do_connection(lp) != 0) {
		univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_WARN, "can not connect to ldap server %s:%d", lp->host, lp->port);
		if (suspend_connect()) {
			if (initialize_only) {
				univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR,
					"can not connect to any ldap server, exit");
				exit(1);
			}
			univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_WARN,
				"can not connect to any ldap server, retrying in 30 seconds");
			sleep(30);
		}

		select_server(lp);
		univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_WARN, "chosen server: %s:%d", lp->host, lp->port);
	}

	univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_INFO, "connection okay to host %s:%d", lp->host, lp->port);

	/* connect to local LDAP server */
	server_role = univention_config_get_string("server/role");
	if ( server_role != NULL ) {
		if (!strcmp(server_role, "domaincontroller_backup") || !strcmp(server_role, "domaincontroller_slave")) {	// if not master
			lp_local->host = strdup("localhost"); // or fqdn e.g. from univention_config_get_string("ldap/server/name");
			lp_local->base = strdup(lp->base);
			lp_local->binddn = strdup(lp->binddn);
			lp_local->bindpw = strdup(lp->bindpw);
		}
		free(server_role);
	}

	/* XXX: we shouldn't block all signals for so long */
	signals_block();
	cache_init();
	handlers_init();

	/* pass data to handlers */
	if (lp->base != NULL)
		handlers_set_data_all("basedn", lp->base);
	if (lp->binddn != NULL)
		handlers_set_data_all("binddn", lp->binddn);
	if (lp->bindpw != NULL)
		handlers_set_data_all("bindpw", lp->bindpw);
	if (lp->host != NULL)
		handlers_set_data_all("ldapserver", lp->host);

	convert_cookie();

	if (notifier_get_id_s(NULL, &id) != 0) {
		univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "failed to receive current ID");
		return 1;
	}

	if (initialize_only) {
		INIT_ONLY=1;
	}

	/* update schema */
	if ((rv=change_update_schema(lp)) != LDAP_SUCCESS)
		return rv;

	/* do initial import of entries */
	if ((rv=change_new_modules(lp)) != LDAP_SUCCESS) {
		univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "change_new_modules: %s", ldap_err2string(rv));
		return rv;
	}
	signals_unblock();

	/* if no ID is set, assume the database has just been initialized */
#ifdef WITH_DB42
	if ((rv=cache_get_master_entry(&master_entry)) == DB_NOTFOUND) {
		master_entry.id = id;
		if ((rv=cache_update_master_entry(&master_entry, NULL)) != 0)
			exit(1);
	} else if (rv != 0)
		exit(1);

#else
	cache_get_int("notifier_id", &old_id, -1);
	if ((long)old_id == -1) {
		cache_set_int("notifier_id", id);
	}
#endif

	if (!initialize_only) {
		rv = notifier_listen(lp, kp, write_transaction_file, lp_local);
	}

	if (rv != 0)
		univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "listener: %d", rv);

	univention_ldap_close(lp);
	univention_ldap_close(lp_local);

	exit_handler(0);
}
Example #27
0
DWORD
VmAfdLDAPConnect(
    PSTR   pszHostName,
    DWORD  dwPort,
    PCSTR   pszUpn,
    PCSTR   pszPassword,
    LDAP** ppLotus
    )
{
    DWORD dwError = 0;
    LDAP* pDirectory = NULL;
    PSTR pszLdapURI = NULL;

    if (dwPort == 0)
    {
        dwPort = LDAP_PORT;
    }

    if (VmAfdIsIPV6AddrFormat(pszHostName))
    {
        dwError = VmAfdAllocateStringPrintf(
                &pszLdapURI,
                "ldap://[%s]:%d",
                pszHostName,
                dwPort);
    }
    else
    {
        dwError = VmAfdAllocateStringPrintf(
                &pszLdapURI,
                "ldap://%s:%d",
                pszHostName,
                dwPort);
    }
    BAIL_ON_VMAFD_ERROR(dwError);

    dwError = VmDirSafeLDAPBind(
                    &pDirectory,
                    pszHostName,
                    pszUpn,
                    pszPassword);
    BAIL_ON_VMAFD_ERROR(dwError);

    *ppLotus = pDirectory;

cleanup:
    VMAFD_SAFE_FREE_MEMORY(pszLdapURI);

    return dwError;

error:

    *ppLotus = NULL;

    if (pDirectory != NULL)
    {
        ldap_unbind_ext(pDirectory, NULL, NULL);
    }

    goto cleanup;
}