static LDAP *ldap_init_and_bind (const char *host, #ifdef WIN32 gboolean use_ssl, #endif const char *user_dn, const char *password) { LDAP *ld; int res; int desired_version = LDAP_VERSION3; #ifndef WIN32 res = ldap_initialize (&ld, host); if (res != LDAP_SUCCESS) { ccnet_warning ("ldap_initialize failed: %s.\n", ldap_err2string(res)); return NULL; } #else char *host_copy = g_strdup (host); if (!use_ssl) ld = ldap_init (host_copy, LDAP_PORT); else ld = ldap_sslinit (host_copy, LDAP_SSL_PORT, 1); g_free (host_copy); if (!ld) { ccnet_warning ("ldap_init failed: %ul.\n", LdapGetLastError()); return NULL; } #endif /* set the LDAP version to be 3 */ res = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &desired_version); if (res != LDAP_OPT_SUCCESS) { ccnet_warning ("ldap_set_option failed: %s.\n", ldap_err2string(res)); return NULL; } if (user_dn) { #ifndef WIN32 res = ldap_bind_s (ld, user_dn, password, LDAP_AUTH_SIMPLE); #else char *dn_copy = g_strdup(user_dn); char *password_copy = g_strdup(password); res = ldap_bind_s (ld, dn_copy, password_copy, LDAP_AUTH_SIMPLE); g_free (dn_copy); g_free (password_copy); #endif if (res != LDAP_SUCCESS ) { ccnet_warning ("ldap_bind failed: %s.\n", ldap_err2string(res)); ldap_unbind_s (ld); return NULL; } } return ld; }
/* ** Open and initialize a connection to a server. ** @param #1 String with hostname. ** @param #2 String with username. ** @param #3 String with password. ** @param #4 Boolean indicating if TLS must be used. ** @return #1 Userdata with connection structure. */ static int lualdap_open_simple (lua_State *L) { ldap_pchar_t host = (ldap_pchar_t) luaL_checkstring (L, 1); ldap_pchar_t who = (ldap_pchar_t) luaL_optstring (L, 2, NULL); const char *password = luaL_optstring (L, 3, NULL); int use_tls = lua_toboolean (L, 4); conn_data *conn = (conn_data *)lua_newuserdata (L, sizeof(conn_data)); int err; /* Initialize */ lualdap_setmeta (L, LUALDAP_CONNECTION_METATABLE); conn->version = 0; conn->ld = ldap_init (host, LDAP_PORT); if (conn->ld == NULL) return faildirect(L,LUALDAP_PREFIX"Error connecting to server"); /* Set protocol version */ conn->version = LDAP_VERSION3; if (ldap_set_option (conn->ld, LDAP_OPT_PROTOCOL_VERSION, &conn->version) != LDAP_OPT_SUCCESS) return faildirect(L, LUALDAP_PREFIX"Error setting LDAP version"); /* Use TLS */ if (use_tls) { int rc = ldap_start_tls_s (conn->ld, NULL, NULL); if (rc != LDAP_SUCCESS) return faildirect (L, ldap_err2string (rc)); } /* Bind to a server */ err = ldap_bind_s (conn->ld, who, password, LDAP_AUTH_SIMPLE); if (err != LDAP_SUCCESS) return faildirect (L, ldap_err2string (err)); return 1; }
static LDAP *ldap_init_and_bind (const char *host, const char *user_dn, const char *password) { LDAP *ld; int res; int desired_version = LDAP_VERSION3; res = ldap_initialize (&ld, host); if (res != LDAP_SUCCESS) { ccnet_warning ("ldap_initialize failed: %s.\n", ldap_err2string(res)); return NULL; } /* set the LDAP version to be 3 */ res = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &desired_version); if (res != LDAP_OPT_SUCCESS) { ccnet_warning ("ldap_set_option failed: %s.\n", ldap_err2string(res)); return NULL; } if (user_dn) { res = ldap_bind_s (ld, user_dn, password, LDAP_AUTH_SIMPLE); if (res != LDAP_SUCCESS ) { ccnet_warning ("ldap_bind failed: %s.\n", ldap_err2string(res)); ldap_unbind_s (ld); return NULL; } } return ld; }
static LDAP *pw_ldap_connect(const char *dn, const char *password) { LDAP *ld; # ifdef LDAP_OPT_PROTOCOL_VERSION int version = ldap_version; # endif if (ldap_uri == NULL) { return NULL; } if (ldap_initialize(&ld, ldap_uri) != LDAP_SUCCESS) { return NULL; } # ifdef LDAP_OPT_PROTOCOL_VERSION if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) != LDAP_SUCCESS) { return NULL; } # endif if (use_tls > 0 && ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { return NULL; } if (ldap_bind_s(ld, dn, password, LDAP_AUTH_SIMPLE) != LDAP_SUCCESS) { return NULL; } return ld; }
LDAPSession::LDAPSession ( string server,int port,string bindDN, string pass, bool simple, bool start_tls ) { ld=ldap_init ( server.c_str(),port ); if ( !ld ) throw LDAPExeption ( "ldap_init","Can't initialize LDAP library." ); int ver=3; int errc=ldap_set_option ( ld,LDAP_OPT_PROTOCOL_VERSION,&ver ); if ( errc != LDAP_SUCCESS ) throw LDAPExeption ( "ldap_set_option", ldap_err2string ( errc ) ); if ( start_tls ) { errc=ldap_start_tls_s ( ld,NULL,NULL ); if ( errc != LDAP_SUCCESS ) throw LDAPExeption ( "ldap_start_tls_s", ldap_err2string ( errc ) ); } if ( !simple ) { errc=ldap_bind_s ( ld,bindDN.c_str(),pass.c_str(), LDAP_AUTH_SIMPLE ); if ( errc != LDAP_SUCCESS ) throw LDAPExeption ( "ldap_bind_s", ldap_err2string ( errc ) ); } else { errc=ldap_simple_bind_s ( ld,bindDN.c_str(),pass.c_str() ); if ( errc != LDAP_SUCCESS ) throw LDAPExeption ( "ldap_simple_bind_s", ldap_err2string ( errc ) ); } }
DWORD LwLdapBindDirectoryAnonymous( HANDLE hDirectory ) { DWORD dwError = 0; PLW_LDAP_DIRECTORY_CONTEXT pDirectory = (PLW_LDAP_DIRECTORY_CONTEXT)hDirectory; LW_BAIL_ON_INVALID_HANDLE(hDirectory); dwError = ldap_bind_s( pDirectory->ld, NULL, NULL, LDAP_AUTH_SIMPLE); BAIL_ON_LDAP_ERROR(dwError); cleanup: return dwError; error: LW_RTL_LOG_ERROR("Failed on LDAP simple bind (Error code: %u)", dwError); if(pDirectory->ld != NULL) { ldap_unbind_s(pDirectory->ld); pDirectory->ld = NULL; } goto cleanup; }
static int bind_prompt( LDAP *ld, LDAP_CONST char *url, ber_tag_t request, ber_int_t msgid, void *params ) { static char dn[256], passwd[256]; int authmethod; printf("rebind for request=%ld msgid=%ld url=%s\n", request, (long) msgid, url ); authmethod = LDAP_AUTH_SIMPLE; get_line( dn, sizeof(dn), stdin, "re-bind dn? " ); strcat( dn, dnsuffix ); if ( authmethod == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) { get_line( passwd, sizeof(passwd), stdin, "re-bind password? " ); } else { passwd[0] = '\0'; } return ldap_bind_s( ld, dn, passwd, authmethod); }
static VALUE rldap_bind(int argc, VALUE *argv, VALUE obj) { RLDAP_WRAP *wrapper; char *bind_dn = NULL, *bind_password = NULL; int retval; VALUE rdn, rpassword; rb_scan_args(argc, argv, "02", &rdn, &rpassword); if (NIL_P(rdn)) bind_dn = NULL; else bind_dn = StringValuePtr(rdn); if (NIL_P(rpassword)) bind_password = NULL; else bind_password = StringValuePtr(rpassword); wrapper = get_wrapper(obj); retval = ldap_bind_s(wrapper->ld, bind_dn, bind_password, LDAP_AUTH_SIMPLE); if (retval != LDAP_SUCCESS) rldap_raise(retval); else return Qtrue; }
int LdapUtils::LdapSimpleBind(LDAP* ld, char* userdn, char* password) { #ifndef _WIN32 TIMEVAL timeout = {LDAPTIMEOUT, 0}; ldap_set_option(ld, LDAP_OPT_TIMEOUT, &timeout); ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &timeout); #endif return ldap_bind_s(ld, userdn, password, LDAP_AUTH_SIMPLE); }
static int ldap_get_fulldn(LD_session *session, char *username, char *userstr, int username_length) { struct berval cred; struct berval *msgidp=NULL; char filter[MAXFILTERSTR], *dn; int rc = 0; char logbuf[MAXLOGBUF]; LDAPMessage *res, *entry; memset(userstr, 0, username_length); cred.bv_val = ldap_authorization_bindpasswd; cred.bv_len = strlen(ldap_authorization_bindpasswd); #if LDAP_API_VERSION > 3000 if((rc = ldap_sasl_bind_s(session->sess, ldap_authorization_binddn, ldap_authorization_type, &cred, NULL, NULL, &msgidp))!=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, ldap_authorization_binddn, ldap_authorization_bindpasswd, 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 /* create filter for search */ memset(filter, 0, MAXFILTERSTR); snprintf(filter, MAXLOGBUF, "(uid=%s)", username); 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_FALSE; } if ((entry = ldap_first_entry(session->sess,res)) == NULL) { return RETURN_FALSE; } else { dn = ldap_get_dn(session->sess, entry); strncpy(userstr, dn, strlen(dn)); }; ldap_msgfree(res); return RETURN_TRUE; }
int LdapUtils::LdapSimpleBind(LDAP* ld, char* userdn, char* password) { #ifndef _WIN32 TIMEVAL timeout = {LDAPTIMEOUT, 0}; ldap_set_option(ld, LDAP_OPT_TIMEOUT, &timeout); ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &timeout); #endif int srtn = ldap_bind_s(ld, userdn, password, LDAP_AUTH_SIMPLE); #ifndef _WIN32 // secure ldap tls might overwrite SIGPIPE handler signal(SIGPIPE, SIG_IGN); #endif return srtn; }
/*% Connects / reconnects to LDAP server */ static isc_result_t dlz_ldap_connect (ldap_instance_t * dbi, dbinstance_t * dbc) { isc_result_t result; int ldap_result; /* if we have a connection, get ride of it. */ if (dbc->dbconn != NULL) { ldap_unbind_s ((LDAP *) dbc->dbconn); dbc->dbconn = NULL; } /* now connect / reconnect. */ /* initialize. */ dbc->dbconn = ldap_init (dbi->hosts, LDAP_PORT); if (dbc->dbconn == NULL) return (ISC_R_NOMEMORY); /* set protocol version. */ ldap_result = ldap_set_option ((LDAP *) dbc->dbconn, LDAP_OPT_PROTOCOL_VERSION, &(dbi->protocol)); if (ldap_result != LDAP_SUCCESS) { result = ISC_R_NOPERM; goto cleanup; } /* "bind" to server. i.e. send username / pass */ ldap_result = ldap_bind_s ((LDAP *) dbc->dbconn, dbi->user, dbi->cred, dbi->method); if (ldap_result != LDAP_SUCCESS) { result = ISC_R_FAILURE; goto cleanup; } return (ISC_R_SUCCESS); cleanup: /* cleanup if failure. */ if (dbc->dbconn != NULL) { ldap_unbind_s ((LDAP *) dbc->dbconn); dbc->dbconn = NULL; } return (result); }
static int auth_ldap_bind(void) { int err; TRACE(TRACE_DEBUG, "binddn [%s]", _ldap_cfg.bind_dn); LDAP *c = ldap_con_get(); if ((err = ldap_bind_s(c, _ldap_cfg.bind_dn, _ldap_cfg.bind_pw, LDAP_AUTH_SIMPLE))) { TRACE(TRACE_ERR, "ldap_bind_s failed: %s", ldap_err2string(err)); return -1; } return 0; }
/* LDAP_rebindproc() openLDAP V3 style * ON ENTRY: * ld Pointer to an LDAP control structure. (input only) * url Unused in this routine * request Unused in this routine * msgid Unused in this routine */ static int LDAP_rebindproc(LDAP *ld, LDAP_CONST char *url, int request, ber_int_t msgid) { apr_ldap_rebind_entry_t *my_conn; const char *bindDN = NULL; const char *bindPW = NULL; my_conn = apr_ldap_rebind_lookup(ld); if ((my_conn) && (my_conn->bindDN != NULL)) { bindDN = my_conn->bindDN; bindPW = my_conn->bindPW; } return (ldap_bind_s(ld, bindDN, bindPW, LDAP_AUTH_SIMPLE)); }
bool AD::Login() { if(!Connect()) { Util::Warn(L"Couldn't connect via LDAP.\n"); wprintf(L"ret = %x\n", LdapGetLastError()); return false; } if(ldap_bind_s(ldap, NULL, NULL, LDAP_AUTH_NEGOTIATE) != LDAP_SUCCESS) { Util::Error(LdapGetLastError(), L"ldap_bind_s()"); return false; } return true; }
BOOL kuhl_m_sid_getLdapAndRootDN(PCWCHAR system, PLDAP *ld, PWCHAR *rootDn) { BOOL status = FALSE; DWORD dwErr; if(*ld = ldap_init((PWCHAR) system, LDAP_PORT)) { if(*rootDn = kuhl_m_sid_getRootDomainNamingContext(*ld)) { dwErr = ldap_bind_s(*ld, NULL, NULL, LDAP_AUTH_NEGOTIATE); status = (dwErr == LDAP_SUCCESS); if(!status) { PRINT_ERROR(L"ldap_bind_s 0x%x (%u)\n", dwErr, dwErr); *rootDn = (PWCHAR) LocalFree(*rootDn); } } if(!status) ldap_unbind(*ld); } else PRINT_ERROR(L"ldap_init\n"); return status; }
LDAP * InitLdap(char *host, char *port) { LDAP *ld; int version; /* Conectarse al servidor */ ld = ldap_open(host,atoi(port)); if( ld == NULL ){ fprintf(stderr,"InitLdap ERROR: No pudo establecerce una coneccion con el servidor LDAP en el host %s:%d\n",host,port); } /* Seteo a la version 3 */ version = LDAP_VERSION3; ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version ); /* Se identifica al usuario root */ if( ldap_bind_s(ld,ADMIN_DN,ADMIN_PASSWD,LDAP_AUTH_SIMPLE) != LDAP_SUCCESS ){ fprintf(stderr,"InitLdap ERROR: El servidor LDAP rechazo el pedido de autentificacion del usuario root %s\n",ADMIN_DN); } /* Se inicializa la base de datos */ if( !RootExists(ld) ) { if( RootAdd(ld) == FATAL_ERROR ) { EndLdap(ld); return NULL; } } if( !ClientListExists(ld) ) { if( ClientsInit(ld) == FATAL_ERROR ) { EndLdap(ld); return NULL; } } return ld; }
//---------------------------------------------------------------------------- // // RestoreDeletedObject() // // Restores a deleted object. // // pwszDeletedDN - Contains the fully-qualified distinguished name of the // deleted object. // // pwszDestContainerDN - Contains the fully-qualified distinguished name of // the folder that the delted object should be moved to. // // Returns S_OK if successful or an HRESULT or LDAP error code otherwise. // //---------------------------------------------------------------------------- HRESULT RestoreDeletedObject(LPCWSTR pwszDeletedDN, LPCWSTR pwszDestContainerDN) { if((NULL == pwszDeletedDN) || (NULL == pwszDestContainerDN)) { return E_POINTER; } HRESULT hr = E_FAIL; // Build the new distinguished name. LPWSTR pwszNewDN = new WCHAR[lstrlenW(pwszDeletedDN) + lstrlenW(pwszDestContainerDN) + 1]; if(pwszNewDN) { lstrcpyW(pwszNewDN, pwszDeletedDN); // Search for the first 0x0A character. This is the delimiter in the deleted object name. LPWSTR pwszChar; for(pwszChar = pwszNewDN; *pwszChar; pwszChar = CharNextW(pwszChar)) { if(('\\' == *pwszChar) && ('0' == *(pwszChar + 1)) && ('A' == *(pwszChar + 2))) { break; } } if(0 != *pwszChar) { // Truncate the name string at the delimiter. *pwszChar = 0; // Add the last known parent DN to complete the DN. lstrcatW(pwszNewDN, L","); lstrcatW(pwszNewDN, pwszDestContainerDN); PLDAP ld; // Initialize LDAP. ld = ldap_init(NULL, LDAP_PORT); if(NULL != ld) { ULONG ulRC; ULONG version = LDAP_VERSION3; // Set the LDAP version. ulRC = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, (void*)&version); if(LDAP_SUCCESS == ulRC) { // Establish a connection with the server. ulRC = ldap_connect(ld, NULL); if(LDAP_SUCCESS == ulRC) { // Bind to the LDAP server. ulRC = ldap_bind_s(ld, NULL, NULL, LDAP_AUTH_NEGOTIATE); if(LDAP_SUCCESS == ulRC) { // Setup the new values. LPWSTR rgNewVals[] = {pwszNewDN, NULL}; /* Remove the isDeleted attribute. This cannot be set to FALSE or the restore operation will not work. */ LDAPModW modIsDeleted = { LDAP_MOD_DELETE, L"isDeleted", NULL }; /* Set the new DN, in effect, moving the deleted object to where it resided before the deletion. */ LDAPModW modDN = { LDAP_MOD_REPLACE, L"distinguishedName", rgNewVals }; // Initialize the LDAPMod structure. PLDAPModW ldapMods[] = { &modIsDeleted, &modDN, NULL }; /* Use the LDAP_SERVER_SHOW_DELETED_OID control to modify deleted objects. */ LDAPControlW showDeletedControl; showDeletedControl.ldctl_oid = LDAP_SERVER_SHOW_DELETED_OID_W; showDeletedControl.ldctl_value.bv_len = 0; showDeletedControl.ldctl_value.bv_val = NULL; showDeletedControl.ldctl_iscritical = TRUE; // Initialzie the LDAPControl structure PLDAPControlW ldapControls[] = { &showDeletedControl, NULL }; /* Modify the specified attributes. This must performed in one step, which is why the LDAP APIs must be used to restore a deleted object. */ ulRC = ldap_modify_ext_sW(ld, (PWCHAR)pwszDeletedDN, ldapMods, ldapControls, NULL); if(LDAP_SUCCESS == ulRC) { hr = S_OK; } else if(LDAP_ALREADY_EXISTS == ulRC) { /* An object already exists with the specified name in the specified target container. At this point, a new name must be selected. */ } } } } if(LDAP_SUCCESS != ulRC) { hr = ulRC; OutputDebugString(ldap_err2string(ulRC)); } // Release the LDAP session. ldap_unbind(ld); } } else { /* If the end of the string is reached before the delimiter is found, just end and fail. */ hr = E_INVALIDARG; } delete pwszNewDN; } else { hr = E_OUTOFMEMORY; } return hr; }
int main (int argc, char *argv[]) { LDAP *ld; LDAPMessage *result; /* should be int result = STATE_UNKNOWN; */ int status = STATE_UNKNOWN; long microsec; double elapsed_time; /* for ldap tls */ int tls; int version=3; /* for entry counting */ LDAPMessage *next_entry; int status_entries = STATE_OK; int num_entries = 0; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (strstr(argv[0],"check_ldaps")) { xasprintf (&progname, "check_ldaps"); } /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); if (strstr(argv[0],"check_ldaps") && ! starttls && ! ssl_on_connect) starttls = TRUE; /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm (timeout_interval); /* get the start time */ gettimeofday (&tv, NULL); /* initialize ldap */ if (ld_uri != NULL) { #ifdef HAVE_LDAP_INITIALIZE int result = ldap_initialize(&ld, ld_uri); if (result != LDAP_SUCCESS) { printf ("Failed to connect to LDAP server at %s: %s\n", ld_uri, ldap_err2string(result)); return STATE_CRITICAL; } #else printf ("Sorry, this version of %s was compiled without URI support!\n", argv[0]); return STATE_CRITICAL; #endif } #ifdef HAVE_LDAP_INIT else if (!(ld = ldap_init (ld_host, ld_port))) { printf ("Could not connect to the server at port %i\n", ld_port); return STATE_CRITICAL; } #else else if (!(ld = ldap_open (ld_host, ld_port))) { if (verbose) ldap_perror(ld, "ldap_open"); printf (_("Could not connect to the server at port %i\n"), ld_port); return STATE_CRITICAL; } #endif /* HAVE_LDAP_INIT */ #ifdef HAVE_LDAP_SET_OPTION /* set ldap options */ if (ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ld_protocol) != LDAP_OPT_SUCCESS ) { printf(_("Could not set protocol version %d\n"), ld_protocol); return STATE_CRITICAL; } #endif if (ld_port == LDAPS_PORT || ssl_on_connect) { xasprintf (&SERVICE, "LDAPS"); #if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS) /* ldaps: set option tls */ tls = LDAP_OPT_X_TLS_HARD; if (ldap_set_option (ld, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldaps_option"); printf (_("Could not init TLS at port %i!\n"), ld_port); return STATE_CRITICAL; } #else printf (_("TLS not supported by the libraries!\n")); return STATE_CRITICAL; #endif /* LDAP_OPT_X_TLS */ } else if (starttls) { xasprintf (&SERVICE, "LDAP-TLS"); #if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S) /* ldap with startTLS: set option version */ if (ldap_get_option(ld,LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS ) { if (version < LDAP_VERSION3) { version = LDAP_VERSION3; ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version); } } /* call start_tls */ if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_start_tls"); printf (_("Could not init startTLS at port %i!\n"), ld_port); return STATE_CRITICAL; } #else printf (_("startTLS not supported by the library, needs LDAPv3!\n")); return STATE_CRITICAL; #endif /* HAVE_LDAP_START_TLS_S */ } /* bind to the ldap server */ if (ldap_bind_s (ld, ld_binddn, ld_passwd, LDAP_AUTH_SIMPLE) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_bind"); printf (_("Could not bind to the LDAP server\n")); return STATE_CRITICAL; } /* do a search of all objectclasses in the base dn */ if (ldap_search_s (ld, ld_base, (crit_entries!=NULL || warn_entries!=NULL) ? LDAP_SCOPE_SUBTREE : LDAP_SCOPE_BASE, ld_attr, NULL, 0, &result) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_search"); printf (_("Could not search/find objectclasses in %s\n"), ld_base); return STATE_CRITICAL; } else if (crit_entries!=NULL || warn_entries!=NULL) { num_entries = ldap_count_entries(ld, result); } /* unbind from the ldap server */ ldap_unbind (ld); /* reset the alarm handler */ alarm (0); /* calcutate the elapsed time and compare to thresholds */ microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (crit_time!=UNDEFINED && elapsed_time>crit_time) status = STATE_CRITICAL; else if (warn_time!=UNDEFINED && elapsed_time>warn_time) status = STATE_WARNING; else status = STATE_OK; if(entries_thresholds != NULL) { if (verbose) { printf ("entries found: %d\n", num_entries); print_thresholds("entry threasholds", entries_thresholds); } status_entries = get_status(num_entries, entries_thresholds); if (status_entries == STATE_CRITICAL) { status = STATE_CRITICAL; } else if (status != STATE_CRITICAL) { status = status_entries; } } /* print out the result */ if (crit_entries!=NULL || warn_entries!=NULL) { printf (_("LDAP %s - found %d entries in %.3f seconds|%s %s\n"), state_text (status), num_entries, elapsed_time, fperfdata ("time", elapsed_time, "s", (int)warn_time, warn_time, (int)crit_time, crit_time, TRUE, 0, FALSE, 0), sperfdata ("entries", (double)num_entries, "", warn_entries, crit_entries, TRUE, 0.0, FALSE, 0.0)); } else { printf (_("LDAP %s - %.3f seconds response time|%s\n"), state_text (status), elapsed_time, fperfdata ("time", elapsed_time, "s", (int)warn_time, warn_time, (int)crit_time, crit_time, TRUE, 0, FALSE, 0)); } return status; }
LDAPConn * nsldapi_new_connection( LDAP *ld, LDAPServer **srvlistp, int use_ldsb, int connect, int bind ) { int rc; LDAPConn *lc; LDAPServer *prevsrv, *srv; Sockbuf *sb = NULL; /* * make a new LDAP server connection */ if (( lc = (LDAPConn *)NSLDAPI_CALLOC( 1, sizeof( LDAPConn ))) == NULL || ( !use_ldsb && ( sb = ber_sockbuf_alloc()) == NULL )) { if ( lc != NULL ) { NSLDAPI_FREE( (char *)lc ); } LDAP_SET_LDERRNO( ld, LDAP_NO_MEMORY, NULL, NULL ); return( NULL ); } LDAP_MUTEX_LOCK( ld, LDAP_OPTION_LOCK ); if ( !use_ldsb ) { /* * we have allocated a new sockbuf * set I/O routines to match those in default LDAP sockbuf */ IFP sb_fn; struct lber_x_ext_io_fns extiofns; extiofns.lbextiofn_size = LBER_X_EXTIO_FNS_SIZE; if ( ber_sockbuf_get_option( ld->ld_sbp, LBER_SOCKBUF_OPT_EXT_IO_FNS, &extiofns ) == 0 ) { ber_sockbuf_set_option( sb, LBER_SOCKBUF_OPT_EXT_IO_FNS, &extiofns ); } if ( ber_sockbuf_get_option( ld->ld_sbp, LBER_SOCKBUF_OPT_READ_FN, (void *)&sb_fn ) == 0 && sb_fn != NULL ) { ber_sockbuf_set_option( sb, LBER_SOCKBUF_OPT_READ_FN, (void *)sb_fn ); } if ( ber_sockbuf_get_option( ld->ld_sbp, LBER_SOCKBUF_OPT_WRITE_FN, (void *)&sb_fn ) == 0 && sb_fn != NULL ) { ber_sockbuf_set_option( sb, LBER_SOCKBUF_OPT_WRITE_FN, (void *)sb_fn ); } } lc->lconn_sb = ( use_ldsb ) ? ld->ld_sbp : sb; lc->lconn_version = ld->ld_version; /* inherited */ LDAP_MUTEX_UNLOCK( ld, LDAP_OPTION_LOCK ); if ( connect ) { prevsrv = NULL; /* * save the return code for later */ for ( srv = *srvlistp; srv != NULL; srv = srv->lsrv_next ) { rc = nsldapi_connect_to_host( ld, lc->lconn_sb, srv->lsrv_host, srv->lsrv_port, ( srv->lsrv_options & LDAP_SRV_OPT_SECURE ) != 0, &lc->lconn_krbinstance ); if (rc != -1) { break; } prevsrv = srv; } if ( srv == NULL ) { if ( !use_ldsb ) { NSLDAPI_FREE( (char *)lc->lconn_sb ); } NSLDAPI_FREE( (char *)lc ); /* nsldapi_open_ldap_connection has already set ld_errno */ return( NULL ); } if ( prevsrv == NULL ) { *srvlistp = srv->lsrv_next; } else { prevsrv->lsrv_next = srv->lsrv_next; } lc->lconn_server = srv; } if (ld->ld_options & LDAP_BITOPT_ASYNC && rc == -2) { lc->lconn_status = LDAP_CONNST_CONNECTING; } else { lc->lconn_status = LDAP_CONNST_CONNECTED; } lc->lconn_next = ld->ld_conns; ld->ld_conns = lc; /* * XXX for now, we always do a synchronous bind. This will have * to change in the long run... */ if ( bind ) { int err, lderr, freepasswd, authmethod; char *binddn, *passwd; LDAPConn *savedefconn; freepasswd = err = 0; if ( ld->ld_rebind_fn == NULL ) { binddn = passwd = ""; authmethod = LDAP_AUTH_SIMPLE; } else { if (( lderr = (*ld->ld_rebind_fn)( ld, &binddn, &passwd, &authmethod, 0, ld->ld_rebind_arg )) == LDAP_SUCCESS ) { freepasswd = 1; } else { LDAP_SET_LDERRNO( ld, lderr, NULL, NULL ); err = -1; } } if ( err == 0 ) { savedefconn = ld->ld_defconn; ld->ld_defconn = lc; ++lc->lconn_refcnt; /* avoid premature free */ /* * when binding, we will back down as low as LDAPv2 * if we get back "protocol error" from bind attempts */ for ( ;; ) { /* LDAP_MUTEX_UNLOCK(ld, LDAP_CONN_LOCK); */ if (( lderr = ldap_bind_s( ld, binddn, passwd, authmethod )) == LDAP_SUCCESS ) { /* LDAP_MUTEX_LOCK(ld, LDAP_CONN_LOCK); */ break; } /* LDAP_MUTEX_LOCK(ld, LDAP_CONN_LOCK); */ if ( lc->lconn_version <= LDAP_VERSION2 || lderr != LDAP_PROTOCOL_ERROR ) { err = -1; break; } --lc->lconn_version; /* try lower version */ } --lc->lconn_refcnt; ld->ld_defconn = savedefconn; } if ( freepasswd ) { (*ld->ld_rebind_fn)( ld, &binddn, &passwd, &authmethod, 1, ld->ld_rebind_arg ); } if ( err != 0 ) { nsldapi_free_connection( ld, lc, NULL, NULL, 1, 0 ); lc = NULL; } } return( lc ); }
/* return 0 IFF op_dn is a value in group_at (member) attribute * of entry with gr_dn AND that entry has an objectClass * value of group_oc (groupOfNames) */ int ldap_back_group( Backend *be, Connection *conn, Operation *op, Entry *target, struct berval *gr_ndn, struct berval *op_ndn, ObjectClass *group_oc, AttributeDescription* group_at ) { struct ldapinfo *li = (struct ldapinfo *) be->be_private; int rc = 1; Attribute *attr; LDAPMessage *result; char *gattr[2]; char *filter = NULL, *ptr; LDAP *ld; struct berval mop_ndn = { 0, NULL }, mgr_ndn = { 0, NULL }; AttributeDescription *ad_objectClass = slap_schema.si_ad_objectClass; struct berval group_oc_name = {0, NULL}; struct berval group_at_name = group_at->ad_cname; if( group_oc->soc_names && group_oc->soc_names[0] ) { group_oc_name.bv_val = group_oc->soc_names[0]; } else { group_oc_name.bv_val = group_oc->soc_oid; } if (group_oc_name.bv_val) group_oc_name.bv_len = strlen(group_oc_name.bv_val); if (target != NULL && dn_match( &target->e_nname, gr_ndn ) ) { /* we already have a copy of the entry */ /* attribute and objectclass mapping has already been done */ /* * first we need to check if the objectClass attribute * has been retieved; otherwise we need to repeat the search */ attr = attr_find( target->e_attrs, ad_objectClass ); if ( attr != NULL ) { /* * Now we can check for the group objectClass value */ if( !is_entry_objectclass( target, group_oc, 0 ) ) { return(1); } /* * This part has been reworked: the group attr compare * fails only if the attribute is PRESENT but the value * is NOT PRESENT; if the attribute is NOT PRESENT, the * search must be repeated as well. * This may happen if a search for an entry has already * been performed (target is not null) but the group * attribute has not been required */ if ((attr = attr_find(target->e_attrs, group_at)) != NULL) { if( value_find_ex( group_at, SLAP_MR_VALUE_NORMALIZED_MATCH, attr->a_vals, op_ndn ) != LDAP_SUCCESS ) return(1); return(0); } /* else: repeat the search */ } /* else: repeat the search */ } /* else: do the search */ /* * Rewrite the op ndn if needed */ #ifdef ENABLE_REWRITE switch ( rewrite_session( li->rwinfo, "bindDn", op_ndn->bv_val, conn, &mop_ndn.bv_val ) ) { case REWRITE_REGEXEC_OK: if ( mop_ndn.bv_val == NULL ) { mop_ndn = *op_ndn; } #ifdef NEW_LOGGING LDAP_LOG( BACK_LDAP, DETAIL1, "[rw] bindDn (op ndn in group): \"%s\" -> \"%s\"\n", op_ndn->bv_val, mop_ndn.bv_val, 0 ); #else /* !NEW_LOGGING */ Debug( LDAP_DEBUG_ARGS, "rw> bindDn (op ndn in group): \"%s\" -> \"%s\"\n%s", op_ndn->bv_val, mop_ndn.bv_val, "" ); #endif /* !NEW_LOGGING */ break; case REWRITE_REGEXEC_UNWILLING: case REWRITE_REGEXEC_ERR: goto cleanup; } /* * Rewrite the gr ndn if needed */ switch ( rewrite_session( li->rwinfo, "searchBase", gr_ndn->bv_val, conn, &mgr_ndn.bv_val ) ) { case REWRITE_REGEXEC_OK: if ( mgr_ndn.bv_val == NULL ) { mgr_ndn = *gr_ndn; } #ifdef NEW_LOGGING LDAP_LOG( BACK_LDAP, DETAIL1, "[rw] searchBase (gr ndn in group): \"%s\" -> \"%s\"\n%s", gr_ndn->bv_val, mgr_ndn.bv_val, "" ); #else /* !NEW_LOGGING */ Debug( LDAP_DEBUG_ARGS, "rw> searchBase (gr ndn in group):" " \"%s\" -> \"%s\"\n%s", gr_ndn->bv_val, mgr_ndn.bv_val, "" ); #endif /* !NEW_LOGGING */ break; case REWRITE_REGEXEC_UNWILLING: case REWRITE_REGEXEC_ERR: goto cleanup; } #else /* !ENABLE_REWRITE */ ldap_back_dn_massage( li, op_ndn, &mop_ndn, 1, 1 ); if ( mop_ndn.bv_val == NULL ) { goto cleanup; } ldap_back_dn_massage( li, gr_ndn, &mgr_ndn, 1, 1 ); if ( mgr_ndn.bv_val == NULL ) { goto cleanup; } #endif /* !ENABLE_REWRITE */ ldap_back_map(&li->oc_map, &group_oc_name, &group_oc_name, BACKLDAP_MAP); if (group_oc_name.bv_val == NULL || group_oc_name.bv_val[0] == '\0') goto cleanup; ldap_back_map(&li->at_map, &group_at_name, &group_at_name, BACKLDAP_MAP); if (group_at_name.bv_val == NULL || group_at_name.bv_val[0] == '\0') goto cleanup; filter = ch_malloc(sizeof("(&(objectclass=)(=))") + group_oc_name.bv_len + group_at_name.bv_len + mop_ndn.bv_len + 1); if (filter == NULL) goto cleanup; if (ldap_initialize(&ld, li->url) != LDAP_SUCCESS) { goto cleanup; } if (ldap_bind_s(ld, li->binddn, li->bindpw, LDAP_AUTH_SIMPLE) != LDAP_SUCCESS) { goto cleanup; } ptr = lutil_strcopy(filter, "(&(objectclass="); ptr = lutil_strcopy(ptr, group_oc_name.bv_val); ptr = lutil_strcopy(ptr, ")("); ptr = lutil_strcopy(ptr, group_at_name.bv_val); ptr = lutil_strcopy(ptr, "="); ptr = lutil_strcopy(ptr, mop_ndn.bv_val); strcpy(ptr, "))"); gattr[0] = "objectclass"; gattr[1] = NULL; if (ldap_search_ext_s(ld, mgr_ndn.bv_val, LDAP_SCOPE_BASE, filter, gattr, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result) == LDAP_SUCCESS) { if (ldap_first_entry(ld, result) != NULL) rc = 0; ldap_msgfree(result); } cleanup:; if ( ld != NULL ) { ldap_unbind(ld); } ch_free(filter); if ( mop_ndn.bv_val != op_ndn->bv_val ) { free( mop_ndn.bv_val ); } if ( mgr_ndn.bv_val != gr_ndn->bv_val ) { free( mgr_ndn.bv_val ); } return(rc); }
static switch_xml_t xml_ldap_search(const char *section, const char *tag_name, const char *key_name, const char *key_value, switch_event_t *params, void *user_data) { xml_binding_t *binding = (xml_binding_t *) user_data; switch_event_header_t *hi; switch_xml_t xml = NULL, sub = NULL; struct ldap_c ldap_connection; struct ldap_c *ldap = &ldap_connection; int auth_method = LDAP_AUTH_SIMPLE; int desired_version = LDAP_VERSION3; xml_ldap_query_type_t query_type; char *dir_exten = NULL, *dir_domain = NULL; char *search_filter = NULL, *search_base = NULL; int off = 0, ret = 1; //char *buf; //buf = malloc(4096); if (!binding) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No bindings...sorry bud returning now\n"); return NULL; } if (!strcmp(section, "configuration")) { query_type = XML_LDAP_CONFIG; } else if (!strcmp(section, "directory")) { query_type = XML_LDAP_DIRECTORY; } else if (!strcmp(section, "dialplan")) { query_type = XML_LDAP_DIALPLAN; } else if (!strcmp(section, "phrases")) { query_type = XML_LDAP_PHRASE; } else if (!strcmp(section, "languages")) { query_type = XML_LDAP_LANGUAGE; } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid section\n"); return NULL; } if (params) { if ((hi = params->headers)) { for (; hi; hi = hi->next) { switch (query_type) { case XML_LDAP_CONFIG: break; case XML_LDAP_DIRECTORY: if (!strcmp(hi->name, "user")) { dir_exten = strdup(hi->value); } else if (!strcmp(hi->name, "domain")) { dir_domain = strdup(hi->value); } break; case XML_LDAP_DIALPLAN: case XML_LDAP_PHRASE: case XML_LDAP_LANGUAGE: break; } } switch (query_type) { case XML_LDAP_CONFIG: break; case XML_LDAP_DIRECTORY: if (dir_exten && dir_domain) { if ((xml = switch_xml_new("directory"))) { switch_xml_set_attr_d(xml, "type", "freeswitch/xml"); if ((sub = switch_xml_add_child_d(xml, "section", off++))) { switch_xml_set_attr_d(sub, "name", "directory"); } if ((sub = switch_xml_add_child_d(sub, "domain", off++))) { switch_xml_set_attr_d(sub, "name", dir_domain); } if ((sub = switch_xml_add_child_d(sub, "user", off++))) { switch_xml_set_attr_d(sub, "id", dir_exten); } } search_filter = switch_mprintf(binding->filter, dir_exten); search_base = switch_mprintf(binding->basedn, dir_domain); free(dir_exten); dir_exten = NULL; free(dir_domain); dir_domain = NULL; } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Something bad happened during the query construction phase likely exten(%s) or domain(%s) is null\n", dir_exten, dir_domain); goto cleanup; } break; case XML_LDAP_DIALPLAN: if ((xml = switch_xml_new("document"))) { switch_xml_set_attr_d(xml, "type", "freeswitch/xml"); if ((sub = switch_xml_add_child_d(xml, "section", off++))) { switch_xml_set_attr_d(sub, "name", "dialplan"); } sub = switch_xml_add_child_d(xml, "context", off++); } break; case XML_LDAP_PHRASE: case XML_LDAP_LANGUAGE: break; } } else { goto cleanup; } } if ((ldap->ld = (LDAP *) ldap_init(binding->host, LDAP_PORT)) == NULL) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to connect to ldap server.%s\n", binding->host); goto cleanup; } if (ldap_set_option(ldap->ld, LDAP_OPT_PROTOCOL_VERSION, &desired_version) != LDAP_OPT_SUCCESS) { goto cleanup; } ldap_set_option(ldap->ld, LDAP_OPT_X_SASL_SECPROPS, &ldap->sp); if (binding->binddn) { if (ldap_bind_s(ldap->ld, binding->binddn, binding->bindpass, auth_method) != LDAP_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to bind to ldap server %s as %s\n", binding->host, binding->binddn); goto cleanup; } } else { if (ldap_sasl_interactive_bind_s (ldap->ld, NULL, binding->defaults->mech, NULL, NULL, (unsigned) (intptr_t) LDAP_SASL_SIMPLE, lutil_sasl_interact, binding->defaults) != LDAP_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to sasl_bind to ldap server %s as %s\n", binding->host, binding->defaults->authcid); goto cleanup; } } if (ldap_search_s(ldap->ld, search_base, LDAP_SCOPE_SUBTREE, search_filter, NULL, 0, &ldap->msg) != LDAP_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Query failed: -b \"%s\" \"%s\"\n", search_base, search_filter); goto cleanup; } if (ldap_count_entries(ldap->ld, ldap->msg) <= 0) { goto cleanup; } if (sub && xml_ldap_result(&ldap_connection, binding, &sub, &off, query_type) != SWITCH_STATUS_SUCCESS) { goto cleanup; } ret = 0; cleanup: if (ldap->msg) { ldap_msgfree(ldap->msg); } if (ldap->ld) { ldap_unbind_s(ldap->ld); } switch_safe_free(search_filter); switch_safe_free(search_base); //switch_xml_toxml_buf(xml,buf,0,0,1); //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Providing:\n%s\n", buf); if (ret) { switch_xml_free(xml); return NULL; } return xml; }
static void do_modrdn( char *uri, char *host, int port, char *manager, char *passwd, char *entry, int maxloop ) { LDAP *ld = NULL; int i; pid_t pid; char *DNs[2]; char *rdns[2]; pid = getpid(); DNs[0] = entry; DNs[1] = strdup( entry ); /* reverse the RDN, make new DN */ { char *p1, *p2; 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] = ','; } if ( uri ) { ldap_initialize( &ld, uri ); } else { ld = ldap_init( host, port ); } if ( ld == NULL ) { perror( "ldap_init" ); exit( EXIT_FAILURE ); } { int version = LDAP_VERSION3; (void) ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version ); } if ( ldap_bind_s( ld, manager, passwd, LDAP_AUTH_SIMPLE ) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_bind" ); exit( EXIT_FAILURE ); } fprintf( stderr, "PID=%ld - Modrdn(%d): entry=\"%s\".\n", (long) pid, maxloop, entry ); for ( i = 0; i < maxloop; i++ ) { int rc; if (( rc = ldap_modrdn2_s( ld, DNs[0], rdns[0], 0 )) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_modrdn" ); if ( rc != LDAP_NO_SUCH_OBJECT ) break; continue; } if (( rc = ldap_modrdn2_s( ld, DNs[1], rdns[1], 1 )) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_modrdn" ); if ( rc != LDAP_NO_SUCH_OBJECT ) break; continue; } } fprintf( stderr, " PID=%ld - Modrdn done.\n", (long) pid ); ldap_unbind( ld ); }
static int ldap_pap_auth(char *user, char *password, char **msgp, struct wordlist **paddrs, struct wordlist **popts) { int rc,ldap_errno; int version = LDAP_VERSION3; char filter[LDAP_FILT_MAXSIZ]; char userdn[MAX_BUF]; char **ldap_values; LDAP *ldap; LDAPMessage *ldap_mesg; LDAPMessage *ldap_entry; /* Initiate session and bind to LDAP server */ if ((ldap = ldap_init(ldap_host, ldap_port)) == NULL) { error("LDAP: failed to initialize session\n"); return -1; } /* Set LDAP specific options such as timeout, version and tls */ if ((rc = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &version) != LDAP_OPT_SUCCESS)) { error("LDAP: failed to set protocol version\n"); return -1; } if ((rc = ldap_set_option(ldap, LDAP_OPT_NETWORK_TIMEOUT, &ldap_nettimeout) != LDAP_OPT_SUCCESS)) { error("LDAP: failed to set network timeout version\n"); return -1; } if ((rc = ldap_set_option(ldap, LDAP_OPT_TIMELIMIT, &ldap_timeout) != LDAP_OPT_SUCCESS)) { error("LDAP: failed to set timeout option\n"); return -1; } #ifdef OPT_WITH_TLS /* Some servers support only LDAPS but not TLS */ if ((ldap_port == LDAPS_PORT) && ldap_usetls) { int tls_opt = LDAP_OPT_X_TLS_HARD; if ((rc = ldap_set_option(ldap, LDAP_OPT_X_TLS, (void *)&tls_opt)) != LDAP_SUCCESS) { ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &ldap_errno); error("LDAP: failed to set TLS option: %s\n", ldap_err2string(rc)); return -1; } } if (ldap_usetls) { #ifdef DEBUG info("LDAP: Setting TLS option -> ON\n"); #endif if((rc = ldap_start_tls_s(ldap, NULL, NULL) != LDAP_SUCCESS)) { ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &ldap_errno); error("LDAP: failed to initiate TLS: %s\n", ldap_err2string(ldap_errno)); return -1; } } #endif /* Perform binding at last */ if ((rc = ldap_bind_s(ldap, ldap_dn, ldap_pw, LDAP_AUTH_SIMPLE)) != LDAP_SUCCESS) { ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &ldap_errno); error("LDAP: failed to bind: %s\n",ldap_err2string(rc)); ldap_unbind(ldap); return -1; } /* Form a search filter from supplied peer's credentials */ if ((rc = snprintf(filter, LDAP_FILT_MAXSIZ,"(uid=%s)", user)) == -1) { error("LDAP: LDAP filter too big\n"); ldap_unbind(ldap); return -1; }; #ifdef DEBUG info("LDAP: search filter: %s\n",filter); #endif /* Perform search*/ if ((rc = ldap_search_s(ldap, userbasedn, LDAP_SCOPE_SUBTREE, filter, NULL, 0, &ldap_mesg)) != LDAP_SUCCESS) { ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &ldap_errno); error("LDAP: Can't perform search: %s\n", ldap_err2string(rc)); ldap_unbind(ldap); return -1; }; /* If search returned more than 2 results or 0 - something is wrong! */ if ( ldap_mesg == NULL ){ info("LDAP: No such user \"%s\"\n",user); ldap_unbind(ldap); return -1; } if ((ldap_count_entries(ldap, ldap_mesg)) > 1){ warn("LDAP: more than one user \"%s\" exists!\n",user); ldap_unbind(ldap); return -1; } /* Check existance of dialupAccess attribute and it's value */ #ifdef DEBUG info("LDAP: found %u entries\n",ldap_count_entries(ldap, ldap_mesg)); #endif ldap_entry = ldap_first_entry(ldap, ldap_mesg); if ((rc = snprintf(userdn,MAX_BUF,"%s",ldap_get_dn(ldap,ldap_entry))) == -1) warn("LDAP: user DN stripped\n"); #ifdef DEBUG info("LDAP: rebind DN: %s\n",userdn); #endif if ((rc = ldap_simple_bind_s(ldap,userdn,password)) != LDAP_SUCCESS) { error("LDAP: username or password incorrect\n"); *msgp = "Username or password incorrect!"; ldap_unbind(ldap); ldap_msgfree(ldap_mesg); return 0; } /* Set pppd options */ ldap_setoptions(ldap, ldap_mesg, &ldap_data); #ifdef DEBUG info("LDAP: Auth success\n"); #endif *msgp = "Access OK!"; ldap_data.access_ok = 1; /* Write ppp_utmp data in place */ return 1; }
int main( int argc, char *argv[] ) { LDAP *ld; int result; int auth_method = LDAP_AUTH_SIMPLE; int desired_version = LDAP_VERSION3; char *ldap_host = "localhost"; char *root_dn = "cn=Manager, dc=example, dc=com"; char *root_pw = "secret"; BerElement* ber; LDAPMessage* msg; LDAPMessage* entry; char* base="ou=developers,dc=example,dc=com"; char* filter="(objectClass=*)"; char* errstring; char* dn = NULL; char* attr; char** vals; int i; if ((ld = ldap_init(ldap_host, LDAP_PORT)) == NULL ) { perror( "ldap_init failed" ); exit( EXIT_FAILURE ); } /* set the LDAP version to be 3 */ if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &desired_version) != LDAP_OPT_SUCCESS) { ldap_perror(ld, "ldap_set_option"); exit(EXIT_FAILURE); } if (ldap_bind_s(ld, root_dn, root_pw, auth_method) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_bind" ); exit( EXIT_FAILURE ); } if (ldap_search_s(ld, base, LDAP_SCOPE_SUBTREE, filter, NULL, 0, &msg) != LDAP_SUCCESS) { ldap_perror( ld, "ldap_search_s" ); exit(EXIT_FAILURE); } printf("The number of entries returned was %d\n\n", ldap_count_entries(ld, msg)); /* Iterate through the returned entries */ for(entry = ldap_first_entry(ld, msg); entry != NULL; entry = ldap_next_entry(ld, entry)) { if((dn = ldap_get_dn(ld, entry)) != NULL) { printf("Returned dn: %s\n", dn); ldap_memfree(dn); } for( attr = ldap_first_attribute(ld, entry, &ber); attr != NULL; attr = ldap_next_attribute(ld, entry, ber)) { if ((vals = ldap_get_values(ld, entry, attr)) != NULL) { for(i = 0; vals[i] != NULL; i++) { printf("%s: %s\n", attr, vals[i]); } ldap_value_free(vals); } ldap_memfree(attr); } if (ber != NULL) { ber_free(ber,0); } printf("\n"); } /* clean up */ ldap_msgfree(msg); result = ldap_unbind_s(ld); if (result != 0) { fprintf(stderr, "ldap_unbind_s: %s\n", ldap_err2string(result)); exit( EXIT_FAILURE ); } return EXIT_SUCCESS; }
int is_admin(struct rekey_session *sess) { static int ldap_initialized=0; char *username=NULL; LDAP *l=NULL; int v, ssl_hard=LDAP_OPT_X_TLS_HARD, rc, ret=0; struct timeval tv; LDAPMessage *response=NULL; char *reason, *filter; char *ldap_url, *ldap_base, *ldap_filter, *ldap_binddn; char *ldap_pwfile, *ldap_cacertdir; char ldap_pwbuf[257]; #ifdef HAVE_KRB5_REALM krb5_realm *realm; #else krb5_data rdata; krb5_data *realm = &rdata; #endif #if !defined(LDAP_OPT_X_TLS_PROTOCOL_MIN) SSL_CTX *sslctx; #endif if (!princ_ncomp_eq(sess->kctx, sess->princ, 2) || !compare_princ_comp(sess->kctx, sess->princ, 1, "admin")) { goto freeall; } if (!(username=dup_comp_string(sess->kctx, sess->princ, 0))) { prtmsg("Failed to extract username for admin check"); goto freeall; } #ifdef HAVE_KRB5_REALM realm=sess->realm; #else rdata.data=sess->realm; rdata.length=strlen(sess->realm); #endif krb5_appdefault_string(sess->kctx, "rekey", realm, "ldap_uri", LDAP_URI, &ldap_url); krb5_appdefault_string(sess->kctx, "rekey", realm, "ldap_base", LDAP_BASEDN, &ldap_base); krb5_appdefault_string(sess->kctx, "rekey", realm, "ldap_filter", USER_INGROUP_FILTER, &ldap_filter); krb5_appdefault_string(sess->kctx, "rekey", realm, "ldap_binddn", LDAP_BINDDN, &ldap_binddn); krb5_appdefault_string(sess->kctx, "rekey", realm, "ldap_pwfile", LDAP_PWFILE, &ldap_pwfile); krb5_appdefault_string(sess->kctx, "rekey", realm, "ldap_cacertdir", "/etc/andy/ldapcerts", &ldap_cacertdir); if (strlen(ldap_pwfile) > 0) { int fd=open(ldap_pwfile, O_RDONLY); ssize_t rsize; if (fd < 0) { prtmsg("Failed to open LDAP password file %s: %s", ldap_pwfile, strerror(errno)); goto freeall; } rsize=read(fd, ldap_pwbuf, 256); if (rsize < 0) { prtmsg("Failed to read from LDAP password file %s: %s", ldap_pwfile, strerror(errno)); goto freeall; } if (rsize > 255) { prtmsg("LDAP password file %s is too large. limit to 255 characters", ldap_pwfile); goto freeall; } while(rsize > 0 && isspace(ldap_pwbuf[rsize-1])) rsize--; ldap_pwbuf[rsize]=0; } if (!ldap_initialized) { LDAP_SET_OPTION(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ssl_hard); LDAP_SET_OPTION(NULL, LDAP_OPT_X_TLS_CACERTDIR, ldap_cacertdir); LDAP_SET_OPTION(NULL, LDAP_OPT_X_TLS_CIPHER_SUITE, "HIGH:!ADH:!eNULL:-SSLv2"); #if defined(LDAP_OPT_X_TLS_PROTOCOL_MIN) v=LDAP_OPT_X_TLS_PROTOCOL_TLS1_0; LDAP_SET_OPTION(NULL, LDAP_OPT_X_TLS_PROTOCOL_MIN, &v); #else extern int ldap_pvt_tls_init(); extern int ldap_pvt_tls_init_def_ctx( int is_server ); ldap_pvt_tls_init(); ldap_pvt_tls_init_def_ctx(0); LDAP_GET_OPTION(NULL, LDAP_OPT_X_TLS_CTX, &sslctx); if (sslctx) { SSL_CTX_set_options(sslctx, SSL_OP_NO_SSLv2); SSL_CTX_set_options(sslctx, SSL_OP_NO_SSLv3); } #endif ldap_initialized=1; } errno=0; rc = ldap_initialize(&l, ldap_url); if (rc!=LDAP_SUCCESS) { prtmsg("Failed to initialize ldap for %s: %s%s%s", ldap_url, ldap_err2string(rc),(errno==0)?"":": ", (errno==0)?"":strerror(errno)); goto freeall; } v=LDAP_VERSION3; LDAP_SET_OPTION(l, LDAP_OPT_PROTOCOL_VERSION, &v); LDAP_SET_OPTION(l, LDAP_OPT_X_TLS, &ssl_hard); errno=0; #if 0 rc = ldap_sasl_interactive_bind_s(l, NULL, "GSSAPI", NULL, NULL, LDAP_SASL_QUIET, do_sasl_interact, NULL); #else rc = ldap_bind_s(l, ldap_binddn, ldap_pwbuf, LDAP_AUTH_SIMPLE); #endif if (rc!=LDAP_SUCCESS) { prtmsg("Failed to connect or authenticate to ldap for %s: %s%s%s", LDAP_URI, ldap_err2string(rc),(errno==0)?"":": ", (errno==0)?"":strerror(errno)); goto freeall; } tv.tv_sec=30; tv.tv_usec=0; rc = ldap_search_ext_s(l, rekey_admin_group, LDAP_SCOPE_BASE, NO_FILTER, no_attrs, 0, NULL, NULL, &tv, LDAP_NO_LIMIT, &response); if (rc != LDAP_SUCCESS) { prtmsg("Failed to verify group %s existence (searching): %s%s%s", rekey_admin_group, ldap_err2string(rc),(errno==0)?"":": ", (errno==0)?"":strerror(errno)); goto freeall; } reason=aasprintf("verify group %s existence", rekey_admin_group); if (!verify_op_success(l, reason, response)) goto freeall; ldap_msgfree(response); response=NULL; filter=aasprintf(ldap_filter, username, rekey_admin_group); rc = ldap_search_ext_s(l, ldap_base, LDAP_SCOPE_SUB, filter, no_attrs, 0, NULL, NULL, &tv, LDAP_NO_LIMIT, &response); if (rc != LDAP_SUCCESS) { prtmsg("Failed to check user %s admin permission (searching): %s%s%s", username, ldap_err2string(rc),(errno==0)?"":": ", (errno==0)?"":strerror(errno)); goto freeall; } reason=aasprintf("check user %s admin permission", username); if (!verify_single_result(l, 0, reason, response)) goto freeall; ret=1; freeall: ldap_msgfree(response); if (l) ldap_unbind_ext_s(l, NULL, NULL); free(username); return ret; }
STDMETHODIMP CLDAPQuery::connect( /* [in] */ BSTR username, /* [in] */ BSTR password, /* [in] */ BSTR host, /* [in] */ VARIANT_BOOL usessl, /* [retval][out] */ LONG *connect_id) { m_errorCode = 0L; const ULONG no_limit = LDAP_NO_LIMIT; PLDAP ld = NULL; bool useSSL = (usessl==VARIANT_TRUE)? true : false; bool canFindFromRoot = true; CAttributesSchema *attrsSchema = NULL; ULONG ulPort = useSSL?LDAP_SSL_PORT:LDAP_PORT; PTCHAR port = NULL; CString defaultNamingContext; CString csHost = host; CString hostname = _tcstok_s(csHost.GetBuffer(), _T(":"), &port); if(port && _tcslen(port) > 0) ulPort = _tcstol(port, NULL, 10); csHost.ReleaseBuffer(); try { if (useSSL) { if((ld = ldap_sslinit(hostname.GetBuffer(), ulPort, 1))==NULL) { m_errorCode = LdapGetLastError(); return S_FALSE; } m_errorCode = ldap_set_option(ld, LDAP_OPT_SERVER_CERTIFICATE, &CertRoutine); if (m_errorCode != LDAP_SUCCESS) throw _T("error LDAP_OPT_SERVER_CERTIFICATE"); } else { if((ld = ldap_init(hostname.GetBuffer(), ulPort))==NULL) { m_errorCode = LdapGetLastError(); return S_FALSE; } } const ULONG version = LDAP_VERSION3; m_errorCode = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, (void*)&version); if (m_errorCode != LDAP_SUCCESS) throw _T("error LDAP_OPT_PROTOCOL_VERSION"); m_errorCode = ldap_set_option(ld, LDAP_OPT_SIZELIMIT, (void*)&no_limit); if (m_errorCode != LDAP_SUCCESS) throw _T("error LDAP_OPT_SIZELIMIT"); ld->ld_sizelimit = no_limit; m_errorCode = ldap_set_option(ld, LDAP_OPT_TIMELIMIT, (void*)&no_limit); if (m_errorCode != LDAP_SUCCESS) throw _T("error LDAP_OPT_TIMELIMIT"); ld->ld_timelimit = no_limit; m_errorCode = ldap_connect(ld, 0); if (m_errorCode != LDAP_SUCCESS ) throw _T("error ldap_connect"); m_errorCode = ldap_bind_s(ld, CString(username).GetBuffer(), CString(password).GetBuffer(), LDAP_AUTH_SIMPLE); if (m_errorCode != LDAP_SUCCESS) throw _T("error LDAP_AUTH_SIMPLE"); /* Get the RootDSE and BaseDN attribute (add checks on use this code).*/ CSimpleArray<PTCHAR> a; a.Add(_T("defaultNamingContext")); a.Add(_T("subschemaSubentry")); a.Add(NULL); PLDAPMessage pBaseMsg = NULL; if(ldap_search_s(ld, _T(""), LDAP_SCOPE_BASE, _T("(objectClass=*)"), a.GetData(), 0, &pBaseMsg) == LDAP_SUCCESS) { PLDAPMessage const entry = ldap_first_entry(ld, pBaseMsg); if(entry) { PTCHAR * const pschema = ldap_get_values(ld, entry, _T("subschemaSubentry")); if(pschema) { attrsSchema = new CAttributesSchema(ld, *pschema); ldap_value_free(pschema); } //try to find one item in subtree from root, if found it is Global Catalog search PLDAPSearch const pPages = ldap_search_init_page(ld, NULL, LDAP_SCOPE_SUBTREE, _T("(objectClass=*)"), NULL, 0, NULL, NULL, no_limit, 1, NULL); if(pPages) { PLDAPMessage pMsg = NULL; canFindFromRoot = (ldap_get_next_page_s(ld, pPages, NULL, 1, NULL, &pMsg) == LDAP_SUCCESS); if(pMsg) ldap_msgfree(pMsg); ldap_search_abandon_page(ld, pPages); } PTCHAR * const pDefaultNamingContext = ldap_get_values(ld, entry, _T("defaultNamingContext")); if(pDefaultNamingContext) { defaultNamingContext = *pDefaultNamingContext; ldap_value_free(pDefaultNamingContext); } } ldap_msgfree(pBaseMsg); } ÑConnectInfo * const cinfo = new ÑConnectInfo(ld, attrsSchema, defaultNamingContext, canFindFromRoot); *connect_id = ++m_maxConnectionId; m_connections.Add(*connect_id, cinfo); } catch (PTCHAR /*e*/) { if (ld) ldap_unbind_s(ld); *connect_id = -1; return S_FALSE; } return S_OK; }
// userdn is required for ldap_simple_bind_s, not really necessary for ldap_bind_s. int LdapUtils::LdapBind(LDAP* ld, const char* domain, const char* username, const char* password, const char* userdn, LdapServerType server_type, const char* method) { bool binddone = false; int rc = LDAP_SUCCESS; // By default, use kerberos authentication if((method == NULL) || (strlen(method) == 0) || (stricmp(method, "kerberos") == 0)) { #ifdef _WIN32 if(server_type == ACTIVE_DIRECTORY) { if(username != NULL) { SEC_WINNT_AUTH_IDENTITY secIdent; secIdent.User = (unsigned char*)username; secIdent.UserLength = strlen(username); secIdent.Password = (unsigned char*)password; secIdent.PasswordLength = strlen(password); // Somehow, setting the domain makes it slower secIdent.Domain = (unsigned char*)domain; secIdent.DomainLength = strlen(domain); secIdent.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; int rc = ldap_bind_s(ld, (char*)userdn, (char*)&secIdent, LDAP_AUTH_NEGOTIATE); if(rc != LDAP_SUCCESS) { DBGLOG("ldap_bind_s for user %s failed with %d - %s.", username, rc, ldap_err2string(rc)); return rc; } } else { int rc = ldap_bind_s(ld, NULL, NULL, LDAP_AUTH_NEGOTIATE); if(rc != LDAP_SUCCESS) { DBGLOG("User Authentication Failed - ldap_bind_s for current user failed with %d - %s.", rc, ldap_err2string(rc)); return rc; } } binddone = true; } #endif } if(!binddone) { if(userdn == NULL) { DBGLOG("userdn can't be NULL in order to bind to ldap server."); return LDAP_INVALID_CREDENTIALS; } int rc = LdapSimpleBind(ld, (char*)userdn, (char*)password); if (rc != LDAP_SUCCESS && server_type == OPEN_LDAP && strchr(userdn,',')) { //Fedora389 is happier without the domain component specified StringBuffer cn(userdn); cn.replace(',',(char)NULL); if (cn.length())//disallow call if no cn rc = LdapSimpleBind(ld, (char*)cn.str(), (char*)password); } if (rc != LDAP_SUCCESS ) { // For Active Directory, try binding with NT format username if(server_type == ACTIVE_DIRECTORY) { StringBuffer logonname; logonname.append(domain).append("\\").append(username); rc = LdapSimpleBind(ld, (char*)logonname.str(), (char*)password); if(rc != LDAP_SUCCESS) { #ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE char *msg=NULL; ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg); DBGLOG("LDAP bind error for user %s with %d - %s. %s", logonname.str(), rc, ldap_err2string(rc), msg&&*msg?msg:""); ldap_memfree(msg); #else DBGLOG("LDAP bind error for user %s with 0x%" I64F "x - %s", username, (unsigned __int64) rc, ldap_err2string(rc)); #endif return rc; } } else { DBGLOG("LDAP bind error for user %s with 0x%" I64F "x - %s", username, (unsigned __int64) rc, ldap_err2string(rc)); return rc; } } } return rc; }
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; }
int main( int argc, char **argv ) { LDAP *ld = NULL; int i, c, port, errflg, method, id, msgtype; char line[256], command1, command2, command3; char passwd[64], dn[256], rdn[64], attr[64], value[256]; char filter[256], *host, **types; char **exdn; static const char usage[] = "usage: %s [-u] [-h host] [-d level] [-s dnsuffix] [-p port] [-t file] [-T file]\n"; int bound, all, scope, attrsonly; LDAPMessage *res; LDAPMod **mods, **attrs; struct timeval timeout; char *copyfname = NULL; int copyoptions = 0; LDAPURLDesc *ludp; host = NULL; port = LDAP_PORT; dnsuffix = ""; errflg = 0; while (( c = getopt( argc, argv, "h:d:s:p:t:T:" )) != -1 ) { switch( c ) { case 'd': #ifdef LDAP_DEBUG ldap_debug = atoi( optarg ); #ifdef LBER_DEBUG if ( ldap_debug & LDAP_DEBUG_PACKETS ) { ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ldap_debug ); } #endif #else printf( "Compile with -DLDAP_DEBUG for debugging\n" ); #endif break; case 'h': host = optarg; break; case 's': dnsuffix = optarg; break; case 'p': port = atoi( optarg ); break; case 't': /* copy ber's to given file */ copyfname = strdup( optarg ); /* copyoptions = LBER_TO_FILE; */ break; case 'T': /* only output ber's to given file */ copyfname = strdup( optarg ); /* copyoptions = (LBER_TO_FILE | LBER_TO_FILE_ONLY); */ break; default: ++errflg; } } if ( host == NULL && optind == argc - 1 ) { host = argv[ optind ]; ++optind; } if ( errflg || optind < argc - 1 ) { fprintf( stderr, usage, argv[ 0 ] ); exit( EXIT_FAILURE ); } printf( "ldap_init( %s, %d )\n", host == NULL ? "(null)" : host, port ); ld = ldap_init( host, port ); if ( ld == NULL ) { perror( "ldap_init" ); exit( EXIT_FAILURE ); } if ( copyfname != NULL ) { if ( ( ld->ld_sb->sb_fd = open( copyfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) { perror( copyfname ); exit ( EXIT_FAILURE ); } ld->ld_sb->sb_options = copyoptions; } bound = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; (void) memset( line, '\0', sizeof(line) ); while ( get_line( line, sizeof(line), stdin, "\ncommand? " ) != NULL ) { command1 = line[0]; command2 = line[1]; command3 = line[2]; switch ( command1 ) { case 'a': /* add or abandon */ switch ( command2 ) { case 'd': /* add */ get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (attrs = get_modlist( NULL, "attr? ", "value? " )) == NULL ) break; if ( (id = ldap_add( ld, dn, attrs )) == -1 ) ldap_perror( ld, "ldap_add" ); else printf( "Add initiated with id %d\n", id ); break; case 'b': /* abandon */ get_line( line, sizeof(line), stdin, "msgid? " ); id = atoi( line ); if ( ldap_abandon( ld, id ) != 0 ) ldap_perror( ld, "ldap_abandon" ); else printf( "Abandon successful\n" ); break; default: printf( "Possibilities: [ad]d, [ab]ort\n" ); } break; case 'b': /* asynch bind */ method = LDAP_AUTH_SIMPLE; get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( method == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) get_line( passwd, sizeof(passwd), stdin, "password? " ); else passwd[0] = '\0'; if ( ldap_bind( ld, dn, passwd, method ) == -1 ) { fprintf( stderr, "ldap_bind failed\n" ); ldap_perror( ld, "ldap_bind" ); } else { printf( "Bind initiated\n" ); bound = 1; } break; case 'B': /* synch bind */ method = LDAP_AUTH_SIMPLE; get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( dn[0] != '\0' ) get_line( passwd, sizeof(passwd), stdin, "password? " ); else passwd[0] = '\0'; if ( ldap_bind_s( ld, dn, passwd, method ) != LDAP_SUCCESS ) { fprintf( stderr, "ldap_bind_s failed\n" ); ldap_perror( ld, "ldap_bind_s" ); } else { printf( "Bind successful\n" ); bound = 1; } break; case 'c': /* compare */ get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); get_line( attr, sizeof(attr), stdin, "attr? " ); get_line( value, sizeof(value), stdin, "value? " ); if ( (id = ldap_compare( ld, dn, attr, value )) == -1 ) ldap_perror( ld, "ldap_compare" ); else printf( "Compare initiated with id %d\n", id ); break; case 'd': /* turn on debugging */ #ifdef LDAP_DEBUG get_line( line, sizeof(line), stdin, "debug level? " ); ldap_debug = atoi( line ); #ifdef LBER_DEBUG if ( ldap_debug & LDAP_DEBUG_PACKETS ) { ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ldap_debug ); } #endif #else printf( "Compile with -DLDAP_DEBUG for debugging\n" ); #endif break; case 'E': /* explode a dn */ get_line( line, sizeof(line), stdin, "dn? " ); exdn = ldap_explode_dn( line, 0 ); for ( i = 0; exdn != NULL && exdn[i] != NULL; i++ ) { printf( "\t%s\n", exdn[i] ); } break; case 'g': /* set next msgid */ get_line( line, sizeof(line), stdin, "msgid? " ); ld->ld_msgid = atoi( line ); break; case 'v': /* set version number */ get_line( line, sizeof(line), stdin, "version? " ); ld->ld_version = atoi( line ); break; case 'm': /* modify or modifyrdn */ if ( strncmp( line, "modify", 4 ) == 0 ) { get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (mods = get_modlist( "mod (0=>add, 1=>delete, 2=>replace -1=>done)? ", "attribute type? ", "attribute value? " )) == NULL ) break; if ( (id = ldap_modify( ld, dn, mods )) == -1 ) ldap_perror( ld, "ldap_modify" ); else printf( "Modify initiated with id %d\n", id ); } else if ( strncmp( line, "modrdn", 4 ) == 0 ) { get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); get_line( rdn, sizeof(rdn), stdin, "newrdn? " ); if ( (id = ldap_modrdn( ld, dn, rdn )) == -1 ) ldap_perror( ld, "ldap_modrdn" ); else printf( "Modrdn initiated with id %d\n", id ); } else { printf( "Possibilities: [modi]fy, [modr]dn\n" ); } break; case 'q': /* quit */ ldap_unbind( ld ); exit( EXIT_SUCCESS ); break; case 'r': /* result or remove */ switch ( command3 ) { case 's': /* result */ get_line( line, sizeof(line), stdin, "msgid (-1=>any)? " ); if ( line[0] == '\0' ) id = -1; else id = atoi( line ); get_line( line, sizeof(line), stdin, "all (0=>any, 1=>all)? " ); if ( line[0] == '\0' ) all = 1; else all = atoi( line ); if (( msgtype = ldap_result( ld, id, all, &timeout, &res )) < 1 ) { ldap_perror( ld, "ldap_result" ); break; } printf( "\nresult: msgtype %d msgid %d\n", msgtype, res->lm_msgid ); handle_result( ld, res ); res = NULL; break; case 'm': /* remove */ get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (id = ldap_delete( ld, dn )) == -1 ) ldap_perror( ld, "ldap_delete" ); else printf( "Remove initiated with id %d\n", id ); break; default: printf( "Possibilities: [rem]ove, [res]ult\n" ); break; } break; case 's': /* search */ get_line( dn, sizeof(dn), stdin, "searchbase? " ); strcat( dn, dnsuffix ); get_line( line, sizeof(line), stdin, "scope (0=baseObject, 1=oneLevel, 2=subtree, 3=children)? " ); scope = atoi( line ); get_line( filter, sizeof(filter), stdin, "search filter (e.g. sn=jones)? " ); types = get_list( "attrs to return? " ); get_line( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); if (( id = ldap_search( ld, dn, scope, filter, types, attrsonly )) == -1 ) { ldap_perror( ld, "ldap_search" ); } else { printf( "Search initiated with id %d\n", id ); } free_list( types ); break; case 't': /* set timeout value */ get_line( line, sizeof(line), stdin, "timeout? " ); timeout.tv_sec = atoi( line ); break; case 'p': /* parse LDAP URL */ get_line( line, sizeof(line), stdin, "LDAP URL? " ); if (( i = ldap_url_parse( line, &ludp )) != 0 ) { fprintf( stderr, "ldap_url_parse: error %d\n", i ); } else { printf( "\t host: " ); if ( ludp->lud_host == NULL ) { printf( "DEFAULT\n" ); } else { printf( "<%s>\n", ludp->lud_host ); } printf( "\t port: " ); if ( ludp->lud_port == 0 ) { printf( "DEFAULT\n" ); } else { printf( "%d\n", ludp->lud_port ); } printf( "\t dn: <%s>\n", ludp->lud_dn ); printf( "\t attrs:" ); if ( ludp->lud_attrs == NULL ) { printf( " ALL" ); } else { for ( i = 0; ludp->lud_attrs[ i ] != NULL; ++i ) { printf( " <%s>", ludp->lud_attrs[ i ] ); } } printf( "\n\t scope: %s\n", ludp->lud_scope == LDAP_SCOPE_BASE ? "baseObject" : ludp->lud_scope == LDAP_SCOPE_ONELEVEL ? "oneLevel" : ludp->lud_scope == LDAP_SCOPE_SUBTREE ? "subtree" #ifdef LDAP_SCOPE_SUBORDINATE : ludp->lud_scope == LDAP_SCOPE_SUBORDINATE ? "children" #endif : "**invalid**" ); printf( "\tfilter: <%s>\n", ludp->lud_filter ); ldap_free_urldesc( ludp ); } break; case 'n': /* set dn suffix, for convenience */ get_line( line, sizeof(line), stdin, "DN suffix? " ); strcpy( dnsuffix, line ); break; case 'o': /* set ldap options */ get_line( line, sizeof(line), stdin, "alias deref (0=never, 1=searching, 2=finding, 3=always)?" ); ld->ld_deref = atoi( line ); get_line( line, sizeof(line), stdin, "timelimit?" ); ld->ld_timelimit = atoi( line ); get_line( line, sizeof(line), stdin, "sizelimit?" ); ld->ld_sizelimit = atoi( line ); LDAP_BOOL_ZERO(&ld->ld_options); get_line( line, sizeof(line), stdin, "Recognize and chase referrals (0=no, 1=yes)?" ); if ( atoi( line ) != 0 ) { LDAP_BOOL_SET(&ld->ld_options, LDAP_BOOL_REFERRALS); get_line( line, sizeof(line), stdin, "Prompt for bind credentials when chasing referrals (0=no, 1=yes)?" ); if ( atoi( line ) != 0 ) { ldap_set_rebind_proc( ld, bind_prompt, NULL ); } } break; case '?': /* help */ printf( "Commands: [ad]d [ab]andon [b]ind\n" " [B]ind async [c]ompare\n" " [modi]fy [modr]dn [rem]ove\n" " [res]ult [s]earch [q]uit/unbind\n\n" " [d]ebug set ms[g]id\n" " d[n]suffix [t]imeout [v]ersion\n" " [?]help [o]ptions" " [E]xplode dn [p]arse LDAP URL\n" ); break; default: printf( "Invalid command. Type ? for help.\n" ); break; } (void) memset( line, '\0', sizeof(line) ); } return( 0 ); }