static void ldapdb_bind(struct ldapdb_data *data, LDAP **ldp) { #ifndef LDAPDB_RFC1823API const int ver = LDAPDB_LDAP_VERSION; #endif if (*ldp != NULL) ldap_unbind(*ldp); *ldp = ldap_open(data->hostname, data->portno); if (*ldp == NULL) return; #ifndef LDAPDB_RFC1823API ldap_set_option(*ldp, LDAP_OPT_PROTOCOL_VERSION, &ver); #endif #ifdef LDAPDB_TLS if (data->tls) { ldap_start_tls_s(*ldp, NULL, NULL); } #endif if (ldap_simple_bind_s(*ldp, data->bindname, data->bindpw) != LDAP_SUCCESS) { ldap_unbind(*ldp); *ldp = NULL; } }
/******************************************************************************* 函数名称 : dot1x_ldap_start_entry 功能描述 : LDAP_START状态入口 输入参数 : sm --- 状态机 输出参数 : 无 返 回 值 : 无 ------------------------------------------------------------ 最近一次修改记录 : 修改作者 : 王群 修改目的 : 新增函数 修改日期 : 2011年6月2日 *******************************************************************************/ void dot1x_ldap_start_entry(struct eapol_state_machine *sm) { LDAP *ldap = NULL; s32 sizelimit_value = 1; s32 version = 3; if (NULL == sm->ldap_sm) { return; } sm->ldap_sm->state = LDAP_START; sm->ldap_sm->req_count = 0; sm->ldap_sm->inform_eapol_flag = 1; /*开启ldap连接*/ ldap = ldap_open(g_dot1x_var.ldap_conf.ldap_host, g_dot1x_var.ldap_conf.ldap_port); if (NULL == ldap) { return; } (void)ldap_set_option(ldap, LDAP_OPT_SIZELIMIT, &sizelimit_value); (void)ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &version); sm->ldap_sm->ldap = ldap; /*将客户端报文中的密码字段保存下来*/ strncpy(sm->ldap_sm->userpw, (s8 *)(((u8 *)((struct eap_hdr *)(sm->eapol_msg->eaphdr) + 1)) + 2 + sm->identityLen), LDAP_PASSWD_LEN - 1); sm->ldap_sm->userpw[LDAP_PASSWD_LEN - 1] = 0; /*开启ldap_start定时器*/ dloop_register_timeout(0, 0, dot1x_ldap_start_timeout, sm); return; }
LDAP * ldap_ssl_open(char *host, int port, char *keyname) { LDAP *ld; int rval; if (port == 0) port = SSL_LDAP_PORT; ld = ldap_open(host, port); Debug(LDAP_DEBUG_TRACE, catgets(slapdcat, 1, 197, "ldap_ssl_open (after ldap_open)\n"), 0, 0, 0); if (ld == NULL) return (NULL); ld->ld_use_ssl = 1; if (keyname) ld->ld_ssl_key = strdup(keyname); if (establish_ssl_connection(ld) != 0) { ldap_ld_free(ld, 1); return (NULL); } return (ld); }
int main(int argc, char *argv[]) { /* declares local vars */ LDAP *ld; int ec; /* Connects to LDAP server */ ld = ldap_open("ldapmaster.prv.nwc.acsalaska.net", 13891); if (!ld) { fprintf(stderr, "unable to connect\n"); return(1); }; /* Binds to connection */ ec = ldap_simple_bind_s(ld, "cn=Directory Manager", "Lwsu@@ps"); if (ec) { fprintf(stderr, "ldap_bind(): %s\n", ldap_err2string(ec)); return(1); }; /* Sets pointer */ db_pointer = ld; /* Creates Account */ if(db_create(argv[1], argv[2], argv[3], argv[4], argv[5])) { fprintf(stderr, "not created\n"); } else { fprintf(stderr, "created\n"); }; /* ends function */ return(0); }
static int init_ldap_connection(LD_session *session) { /* Init LDAP */ #ifdef LDAP_API_FEATURE_X_OPENLDAP if (ldap_authorization_host != NULL && strchr(ldap_authorization_host, '/')) { if(ldap_initialize(&session->sess, ldap_authorization_host)!=LDAP_SUCCESS) { ldap_log(LOG_ERR, "Ldap connection initialize return fail status"); return RETURN_FALSE; } } else { #if LDAP_API_VERSION>3000 ldap_log(LOG_ERR, "Ldap connection initialize return fail status"); return RETURN_FALSE; #else session->sess = ldap_init(ldap_authorization_host, &ldap_authorization_port); #endif } #else session->sess = ldap_open(ldap_authorization_host, ldap_authorization_port); #endif if (session->sess == NULL) { ldap_log(LOG_ERR, "Final check: Ldap connection initialize return fail status"); return RETURN_FALSE; } return RETURN_TRUE; }
char *gfarm_metadb_initialize(void) { int rv; int port; char *e; LDAPMessage *res; if (gfarm_ldap_server_name == NULL) return ("gfarm.conf: ldap_serverhost is missing"); if (gfarm_ldap_server_port == NULL) return ("gfarm.conf: ldap_serverport is missing"); port = strtol(gfarm_ldap_server_port, &e, 0); if (e == gfarm_ldap_server_port || port <= 0 || port >= 65536) return ("gfarm.conf: ldap_serverport: " "illegal value"); if (gfarm_ldap_base_dn == NULL) return ("gfarm.conf: ldap_base_dn is missing"); /* * initialize LDAP */ /* open a connection */ gfarm_ldap_server = ldap_open(gfarm_ldap_server_name, port); if (gfarm_ldap_server == NULL) { switch (errno) { case EHOSTUNREACH: return ("gfarm meta-db ldap_serverhost " "access failed"); case ECONNREFUSED: return ("gfarm meta-db ldap_serverport " "connection refused"); default: return ("gfarm meta-db ldap_server " "access failed"); /*return (strerror(errno));*/ } } /* authenticate as nobody */ rv = ldap_simple_bind_s(gfarm_ldap_server, NULL, NULL); if (rv != LDAP_SUCCESS) return (ldap_err2string(rv)); /* sanity check. base_dn can be accessed? */ rv = ldap_search_s(gfarm_ldap_server, gfarm_ldap_base_dn, LDAP_SCOPE_BASE, "objectclass=top", NULL, 0, &res); if (rv != LDAP_SUCCESS) { if (rv == LDAP_NO_SUCH_OBJECT) return ("gfarm meta-db ldap_base_dn not found"); return ("gfarm meta-db ldap_base_dn access failed"); } ldap_msgfree(res); return (NULL); }
int ldap_add_machine_account(const char *ldap_host, const char *hostname, const char *realm) { LDAP *ld; int ldap_port = LDAP_PORT; char *bind_path; int rc; LDAPMessage *res; void *sasl_defaults; int version = LDAP_VERSION3; bind_path = build_dn(realm); printf("Creating host account for %s@%s\n", hostname, realm); ld = ldap_open(ldap_host, ldap_port); ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version); rc = ldap_sasl_interactive_bind_s(ld, NULL, NULL, NULL, NULL, 0, sasl_interact, NULL); if (rc != LDAP_SUCCESS) { ldap_perror(ld, "ldap_bind"); goto failed; } rc = find_host(ld, &res, bind_path, hostname); if (rc == LDAP_SUCCESS && ldap_count_entries(ld, res) == 1) { printf("Host account for %s already exists\n", hostname); goto finished; } rc = add_host(ld, bind_path, hostname, realm); if (rc != LDAP_SUCCESS) { ldap_perror(ld, "add_host"); goto failed; } rc = find_host(ld, &res, bind_path, hostname); if (rc != LDAP_SUCCESS || ldap_count_entries(ld, res) != 1) { ldap_perror(ld, "find_host test"); goto failed; } printf("Successfully added machine account for %s\n", hostname); finished: free(bind_path); return 0; failed: printf("ldap_add_machine_account failed\n"); free(bind_path); ldap_unbind(ld); return 1; }
/** * Attempt to connect to the server. * Enter: * \param host Host name. * \param port Port number. * \return <i>TRUE</i> if connected successfully. */ gboolean ldaputil_test_connect( const gchar *host, const gint port ) { gboolean retVal = FALSE; LDAP *ld; if( host == NULL ) return retVal; if( port < 1 ) return retVal; ld = ldap_open( host, port ); if( ld != NULL ) { ldap_unbind( ld ); retVal = TRUE; } return retVal; }
/* * Attempt to connect to the server. * Enter: * host Host name * port Port number * Return: TRUE if connected successfully. */ gboolean syldap_test_connect_s( const gchar *host, const gint port ) { gboolean retVal = FALSE; LDAP *ld; if( host == NULL ) return retVal; if( port < 1 ) return retVal; if( ( ld = ldap_open( host, port ) ) != NULL ) { retVal = TRUE; } if( ld != NULL ) { ldap_unbind( ld ); } return retVal; }
/* Initialize LDAP Conn */ void init_ldap_conn () { int result; conn = ldap_open (ldapsystem, LDAP_PORT); if (conn == NULL) { fprintf (stderr, "Error opening Ldap connection: %s\n", strerror (errno)); exit (-1); } result = ldap_simple_bind_s (conn, binddn, bindpw); ldap_result_check ("ldap_simple_bind_s", "LDAP Bind", result); }
int main(int argc, char **argv) { int ch; log_init(1); log_verbose(~0); while ((ch = getopt(argc, argv, "")) != -1) { switch (ch) { default: log_warnx("warn: table-ldap: bad option"); return (1); /* NOTREACHED */ } } argc -= optind; argv += optind; if (argc != 1) { log_warnx("warn: table-ldap: bogus argument(s)"); return (1); } config = argv[0]; if (!ldap_config()) { log_warnx("warn: table-ldap: could not parse config"); return (1); } log_debug("debug: table-ldap: done reading config"); if (!ldap_open()) { log_warnx("warn: table-ldap: failed to connect"); return (1); } log_debug("debug: table-ldap: connected"); table_api_on_update(table_ldap_update); table_api_on_check(table_ldap_check); table_api_on_lookup(table_ldap_lookup); table_api_on_fetch(table_ldap_fetch); table_api_dispatch(); return (0); }
/* connect to the LDAP server */ int ads_connect(ADS_STRUCT *ads) { int version = LDAP_VERSION3; int rc; ads->ld = ldap_open(ads->ldap_server, ads->ldap_port); if (!ads->ld) { return errno; } ldap_set_option(ads->ld, LDAP_OPT_PROTOCOL_VERSION, &version); rc = ldap_sasl_interactive_bind_s(ads->ld, NULL, NULL, NULL, NULL, 0, sasl_interact, NULL); return rc; }
/* * Attempt to connect to the server. * Enter: ldapServer Server to test. * Return: TRUE if connected successfully. Return code set in ldapServer. */ gboolean syldap_test_connect( SyldapServer *ldapServer ) { gboolean retVal = FALSE; LDAP *ld; ldapServer->retVal = MGU_BAD_ARGS; if( ldapServer == NULL ) return retVal; if( ldapServer->hostName == NULL ) return retVal; if( ldapServer->port < 1 ) return retVal; ldapServer->retVal = MGU_LDAP_INIT; if( ( ld = ldap_open( ldapServer->hostName, ldapServer->port ) ) != NULL ) { ldapServer->retVal = MGU_SUCCESS; retVal = TRUE; } if( ld != NULL ) { ldap_unbind( ld ); } return retVal; }
static void ldapdb_bind(const char *zone, struct ldapdb_data *data, LDAP **ldp) { #ifndef LDAPDB_RFC1823API const int ver = LDAPDB_LDAP_VERSION; #endif int failure = 1, counter = 1, rc; /* Make sure we try at least three times to connect+bind * to the LDAP server. Sleep five seconds between each * attempt => 25 seconds before timeout! */ while((failure == 1) && (counter <= 3)) { if (*ldp != NULL) ldap_unbind(*ldp); /* ----------------------------- */ /* -- Connect to LDAP server. -- */ #ifdef LDAP_API_FEATURE_X_OPENLDAP isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_CONTROL, ISC_LOG_DEBUG(2), "LDAP sdb zone '%s': ldap_initialize(%s)", zone, data->url); /* Connect to LDAP server using URL */ rc = ldap_initialize(ldp, data->url); if (rc != LDAP_SUCCESS) { #else *ldp = ldap_open(data->hostname, data->portno); if (*ldp == NULL) { #endif isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, #ifdef LDAP_API_FEATURE_X_OPENLDAP "LDAP sdb zone '%s': ldapdb_bind(): ldap_initialize() failed. LDAP URL: %s", zone, data->url); #else "LDAP sdb zone '%s': ldapdb_bind(): ldap_open() failed.", zone); #endif /* Failed - wait five seconds, then try again. */ goto try_bind_again; } else
/******************************************************************************* 函数名称 : dot1x_reauth_ldap_verify 功能描述 : LDAP_BIND_DN状态绑定验证用户DN 输入参数 : 输出参数 : 无 返 回 值 : 无 ------------------------------------------------------------ 最近一次修改记录 : 修改作者 : 王群 修改目的 : 新增函数 修改日期 : 2011年6月3日 *******************************************************************************/ s32 dot1x_reauth_ldap_verify(struct eapol_state_machine *sm) { s32 retcode = ERROR_SUCCESS; s8 filter[1024]; LDAPMessage *res = NULL; s32 sizelimit_value = 1; s32 version = 3; /*根据用户的dn和密码进行重认证*/ do{ sm->ldap_sm->ldap = ldap_open(g_dot1x_var.ldap_conf.ldap_host, g_dot1x_var.ldap_conf.ldap_port); if (NULL == sm->ldap_sm->ldap) { retcode = !LDAP_SUCCESS; break; } (void)ldap_set_option(sm->ldap_sm->ldap, LDAP_OPT_SIZELIMIT, &sizelimit_value); (void)ldap_set_option(sm->ldap_sm->ldap, LDAP_OPT_PROTOCOL_VERSION, &version); /*绑定管理员*/ retcode = ldap_simple_bind_s(sm->ldap_sm->ldap, g_dot1x_var.ldap_conf.ldap_rootdn, g_dot1x_var.ldap_conf.ldap_rootpw); if (LDAP_SUCCESS != retcode) { break; } snprintf(filter, sizeof(filter), "(%s=%s)", g_dot1x_var.ldap_conf.ldap_filter, sm->identity); /*执行查询操作*/ retcode = ldap_search_s(sm->ldap_sm->ldap, g_dot1x_var.ldap_conf.ldap_basedn, LDAP_SCOPE_SUBTREE, filter, g_ldap_attrs, 0, &res); ldap_msgfree(res); if (LDAP_SUCCESS != retcode) { break; } }while(0); ldap_unbind(sm->ldap_sm->ldap); return retcode; }
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; }
/* Establish a connection to the LDAP server. */ static int dict_ldap_connect(DICT_LDAP *dict_ldap) { char *myname = "dict_ldap_connect"; int rc = 0; #ifdef LDAP_OPT_NETWORK_TIMEOUT struct timeval mytimeval; #endif #if defined(LDAP_API_FEATURE_X_OPENLDAP) || !defined(LDAP_OPT_NETWORK_TIMEOUT) void (*saved_alarm) (int); #endif #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(LBER_OPT_LOG_PRINT_FN) if (dict_ldap->debuglevel > 0 && ber_set_option(NULL, LBER_OPT_LOG_PRINT_FN, (LDAP_CONST *) dict_ldap_logprint) != LBER_OPT_SUCCESS) msg_warn("%s: Unable to set ber logprint function.", myname); #if defined(LBER_OPT_DEBUG_LEVEL) if (ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &(dict_ldap->debuglevel)) != LBER_OPT_SUCCESS) msg_warn("%s: Unable to set BER debug level.", myname); #endif if (ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &(dict_ldap->debuglevel)) != LDAP_OPT_SUCCESS) msg_warn("%s: Unable to set LDAP debug level.", myname); #endif dict_errno = 0; if (msg_verbose) msg_info("%s: Connecting to server %s", myname, dict_ldap->server_host); #ifdef LDAP_OPT_NETWORK_TIMEOUT #ifdef LDAP_API_FEATURE_X_OPENLDAP dict_ldap_set_tls_options(dict_ldap); ldap_initialize(&(dict_ldap->ld), dict_ldap->server_host); #else dict_ldap->ld = ldap_init(dict_ldap->server_host, (int) dict_ldap->server_port); #endif if (dict_ldap->ld == NULL) { msg_warn("%s: Unable to init LDAP server %s", myname, dict_ldap->server_host); dict_errno = DICT_ERR_RETRY; return (-1); } mytimeval.tv_sec = dict_ldap->timeout; mytimeval.tv_usec = 0; if (ldap_set_option(dict_ldap->ld, LDAP_OPT_NETWORK_TIMEOUT, &mytimeval) != LDAP_OPT_SUCCESS) msg_warn("%s: Unable to set network timeout.", myname); #else if ((saved_alarm = signal(SIGALRM, dict_ldap_timeout)) == SIG_ERR) { msg_warn("%s: Error setting signal handler for open timeout: %m", myname); dict_errno = DICT_ERR_RETRY; return (-1); } alarm(dict_ldap->timeout); if (setjmp(env) == 0) dict_ldap->ld = ldap_open(dict_ldap->server_host, (int) dict_ldap->server_port); else dict_ldap->ld = 0; alarm(0); if (signal(SIGALRM, saved_alarm) == SIG_ERR) { msg_warn("%s: Error resetting signal handler after open: %m", myname); dict_errno = DICT_ERR_RETRY; return (-1); } if (dict_ldap->ld == NULL) { msg_warn("%s: Unable to connect to LDAP server %s", myname, dict_ldap->server_host); dict_errno = DICT_ERR_RETRY; return (-1); } #endif /* * v3 support is needed for referral chasing. Thanks to Sami Haahtinen * for the patch. */ #ifdef LDAP_OPT_PROTOCOL_VERSION if (ldap_set_option(dict_ldap->ld, LDAP_OPT_PROTOCOL_VERSION, &dict_ldap->version) != LDAP_OPT_SUCCESS) msg_warn("%s: Unable to set LDAP protocol version", myname); if (msg_verbose) { if (ldap_get_option(dict_ldap->ld, LDAP_OPT_PROTOCOL_VERSION, &dict_ldap->version) != LDAP_OPT_SUCCESS) msg_warn("%s: Unable to get LDAP protocol version", myname); else msg_info("%s: Actual Protocol version used is %d.", myname, dict_ldap->version); } #endif /* * Limit the number of entries returned by each query. */ if (dict_ldap->size_limit) { if (ldap_set_option(dict_ldap->ld, LDAP_OPT_SIZELIMIT, &dict_ldap->size_limit) != LDAP_OPT_SUCCESS) msg_warn("%s: %s: Unable to set query result size limit to %ld.", myname, dict_ldap->ldapsource, dict_ldap->size_limit); } /* * Configure alias dereferencing for this connection. Thanks to Mike * Mattice for this, and to Hery Rakotoarisoa for the v3 update. */ if (ldap_set_option(dict_ldap->ld, LDAP_OPT_DEREF, &(dict_ldap->dereference)) != LDAP_OPT_SUCCESS) msg_warn("%s: Unable to set dereference option.", myname); /* Chase referrals. */ /* * I have no clue where this was originally added so i'm skipping all * tests */ #ifdef LDAP_OPT_REFERRALS if (ldap_set_option(dict_ldap->ld, LDAP_OPT_REFERRALS, dict_ldap->chase_referrals ? LDAP_OPT_ON : LDAP_OPT_OFF) != LDAP_OPT_SUCCESS) msg_warn("%s: Unable to set Referral chasing.", myname); #else if (dict_ldap->chase_referrals) { msg_warn("%s: Unable to set Referral chasing.", myname); } #endif #ifdef LDAP_API_FEATURE_X_OPENLDAP if (dict_ldap->start_tls) { if ((saved_alarm = signal(SIGALRM, dict_ldap_timeout)) == SIG_ERR) { msg_warn("%s: Error setting signal handler for STARTTLS timeout: %m", myname); dict_errno = DICT_ERR_RETRY; return (-1); } alarm(dict_ldap->timeout); if (setjmp(env) == 0) rc = ldap_start_tls_s(dict_ldap->ld, NULL, NULL); else rc = LDAP_TIMEOUT; alarm(0); if (signal(SIGALRM, saved_alarm) == SIG_ERR) { msg_warn("%s: Error resetting signal handler after STARTTLS: %m", myname); dict_errno = DICT_ERR_RETRY; return (-1); } if (rc != LDAP_SUCCESS) { msg_error("%s: Unable to set STARTTLS: %d: %s", myname, rc, ldap_err2string(rc)); dict_errno = DICT_ERR_RETRY; return (-1); } } #endif /* * If this server requires a bind, do so. Thanks to Sam Tardieu for * noticing that the original bind call was broken. */ if (dict_ldap->bind) { if (msg_verbose) msg_info("%s: Binding to server %s as dn %s", myname, dict_ldap->server_host, dict_ldap->bind_dn); rc = dict_ldap_bind_st(dict_ldap); if (rc != LDAP_SUCCESS) { msg_warn("%s: Unable to bind to server %s as %s: %d (%s)", myname, dict_ldap->server_host, dict_ldap->bind_dn, rc, ldap_err2string(rc)); dict_errno = DICT_ERR_RETRY; return (-1); } if (msg_verbose) msg_info("%s: Successful bind to server %s as %s ", myname, dict_ldap->server_host, dict_ldap->bind_dn); } /* Save connection handle in shared container */ DICT_LDAP_CONN(dict_ldap)->conn_ld = dict_ldap->ld; if (msg_verbose) msg_info("%s: Cached connection handle for LDAP source %s", myname, dict_ldap->ldapsource); return (0); }
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; }
static int do_init (LDAP ** ld, const char *uri, int ldapdefport) { int rc; int ldaps; char uribuf[512]; char *p; DBG("do_init():"); ldaps = (strncasecmp (uri, "ldaps://", sizeof ("ldaps://") - 1) == 0); p = strchr (uri, ':'); /* we should be looking for the second instance to find the port number */ if (p != NULL) { p = strchr (p, ':'); } #ifdef HAVE_LDAP_INITIALIZE if (p == NULL && ((ldaps && ldapdefport != LDAPS_PORT) || (!ldaps && ldapdefport != LDAP_PORT))) { /* No port specified in URI and non-default port specified */ snprintf (uribuf, sizeof (uribuf), "%s:%d", uri, ldapdefport); uri = uribuf; } rc = ldap_initialize (ld, uri); #else /* TODO: !HAVE_LDAP_INITIALIZE => no ldaps:// possible? */ if (strncasecmp (uri, "ldap://", sizeof ("ldap://") - 1) != 0) { return LDAP_UNAVAILABLE; } uri += sizeof ("ldap://") - 1; p = strchr (uri, ':'); if (p != NULL) { size_t urilen = (p - uri); if (urilen >= sizeof (uribuf)) { return LDAP_UNAVAILABLE; } memcpy (uribuf, uri, urilen); uribuf[urilen] = '\0'; ldapdefport = atoi (p + 1); uri = uribuf; } # ifdef HAVE_LDAP_INIT *ld = ldap_init (uri, ldapdefport); # else *ld = ldap_open (uri, ldapdefport); # endif rc = (*ld == NULL) ? LDAP_SERVER_DOWN : LDAP_SUCCESS; #endif /* HAVE_LDAP_INITIALIZE */ if (rc == LDAP_SUCCESS && *ld == NULL) { rc = LDAP_UNAVAILABLE; } return rc; }
int main (int argc, char const *argv[]) { /* code */ char hostname[MAXHOSTNAMELEN], *attrs[2], **vals; LDAP *ldap; LDAPMessage *results = NULL, *entry = NULL; int haveGpoDescriptor = 0; int ret, version, i; printf("----------------------------------\n"); printf("Getting host informations...\n"); printf("----------------------------------\n\n"); if(gethostname(hostname,MAXHOSTNAMELEN) == 0){ struct hostent * record = gethostbyname(hostname); struct in_addr * address = ( struct in_addr *) record->h_addr; printf("Hostname: %s\n", hostname); printf("FQDN: %s\n", record->h_name); printf("IP Address: %s\n", inet_ntoa(address->s_addr)); printf("\n\n----------------------------------\n"); printf("Connecting to %s\n",LDAP_SERVER); printf("----------------------------------\n\n"); ldap = (LDAP*) ldap_open(LDAP_SERVER,LDAP_PORT); if(!ldap){ printf("Unable to connect to the LDAP Server\n"); return 1; }else{ version = LDAP_VERSION3; ldap_set_option( ldap, LDAP_OPT_PROTOCOL_VERSION, &version ); printf("Connected to LDAP server: \033[32;mOk\033[00m.\n"); printf("\n\n----------------------------------\n"); printf("Binding...\n"); printf("----------------------------------\n\n"); /* Anonymous binding... Les machines n'ont pas de mot de passe*/ ret = ldap_simple_bind_s(ldap, NULL, NULL); if (ret != LDAP_SUCCESS) { printf("Binding \033[31;mFailed\033[00m\n\n"); char *error; ldap_perror(ldap,error); printf("%s",error); return 1; } printf("Binding: \033[32;mOk\033[00m.\n"); printf("\n\n----------------------------------\n"); printf("Searching for workstation %s in %s\n",hostname, BASE_DN); printf("----------------------------------\n\n"); char context[MAXHOSTNAMELEN + 5]; snprintf(context,MAXHOSTNAMELEN + 5, "(cn=%s)",hostname); ret = ldap_search_s( ldap, BASE_DN, LDAP_SCOPE_SUBTREE, context, NULL, 0, &results); if(ret != LDAP_SUCCESS){ printf("Unable to perform search\n"); char *error; ldap_perror(ldap,error); printf("%s",error); } entry = ldap_first_entry(ldap, results); if (!entry) { printf("\033[33;m%s workstation not found !\033[00m\n", hostname); return 1; }else{ printf("\033[33;m%s workstation found !\033[00m\n", hostname); } printf("\n\n----------------------------------\n"); printf("Getting OU container name of %s\n",context); printf("----------------------------------\n\n"); vals = (char**) ldap_get_values(ldap,entry,"ou"); char *ou = NULL; for(i=0;vals[i] != NULL;i++){ ou = vals[i]; printf("\033[33;mOU [%d] name of %s: %s\033[00m\n",i,context,vals[i]); break; } printf("\n\n----------------------------------\n"); printf("Searching groupPolicyDescriptor into OU container name: %s of %s\n",ou,context); printf("----------------------------------\n\n"); vals = (char**) ldap_get_values(ldap,entry,"objectClass"); for(i=0;vals[i] != NULL;i++){ if (strcmp(vals[i],"groupPolicyDescriptor") ) { haveGpoDescriptor = 1; printf("\033[33;mGPO Found !\033[00m\n"); char **uri = ldap_get_values(ldap,entry,"uri"); printf("\033[33;mScript path: %s !\033[00m\n",uri[0]); // system("/bin/sh -c %s"); %s = uri[0] break; } } printf("\n\n----------------------------------\n"); printf("Cleaning memory\n"); printf("----------------------------------\n\n"); ldap_value_free(vals); ldap_msgfree(entry); ldap_unbind(ldap); } }else{ printf("Cannot get the hostname.\n"); } return 0; }
int main (int argc, char const *argv[]) { /* code */ pam_handle_t *pamh = NULL; char *user, *password , **userVals = NULL, **ouVals = NULL, **uriVals = NULL, *context; LDAP *ldap = NULL; LDAPMessage *userResults = NULL,*ouResults = NULL, *userEntry = NULL, *ouEntry = NULL; //bool haveGpoDescriptor = 0; user = getlogin(); int pamretval, ret, version, i = 0 ,j = 0, k = 0; printf("----------------------------------\n"); printf("Getting session informations...\n"); printf("----------------------------------\n\n"); pamretval = pam_start("custom",user,&conv,&pamh); if(pamretval == PAM_SUCCESS ){ /* TODO: ------------------------------------------------------------- Si pam_start(...) renvoie PAM_SUCCESS alors récuperer: - username - password */ printf("Logged as: \033[32;m%s\033[00m.\n",user); printf("\n\n----------------------------------\n"); printf("Connecting to %s\n",LDAP_SERVER); printf("----------------------------------\n\n"); ldap = (LDAP*) ldap_open(LDAP_SERVER,LDAP_PORT); if(!ldap){ printf("Unable to connect to the LDAP Server\n"); return PAM_SUCCESS; // Don't break the PAM Stack }else{ version = LDAP_VERSION3; ldap_set_option( ldap, LDAP_OPT_PROTOCOL_VERSION, &version ); printf("Connected to LDAP server: \033[32;mOk\033[00m.\n"); printf("\n\n----------------------------------\n"); printf("Binding...\n"); printf("----------------------------------\n\n"); /* Anonymous Binding */ ret = ldap_simple_bind_s(ldap, NULL, NULL); if (ret != LDAP_SUCCESS) { printf("Binding \033[31;mFailed\033[00m\n\n"); char *error; ldap_perror(ldap,error); printf("%s",error); return PAM_SUCCESS; } printf("Binding: \033[32;mOk\033[00m.\n"); /* TODO <Version compliquée> -------------------------------------------------- Note: Créer autant de LDAPMessage *results qu'il ya de recherche à faire ldap_get_values return char** (un tableau/array) context = (cn | ou = <username | ou_name) ------ 1. Récupérer l'utilisateur -> ldap_search_s(ldap,BASE_DN,LDAP_SCOPE_SUBTREE,context,NULL,0,&userResults); context = (cn=username) -> userEntry = ldap_get_first_entry(ldap,userResults); 2. Récupérer le nom de l'OU (OrganizationalUnit) de l'utilisateur -> char ou_name = ldap_get_values(ldap,userEntry,"ou") 3. Récupérer l'OU en faisant une nouvelle recherche -> ldap_search_s(ldap,BASE_DN,LDAP_SCOPE_SUBTREE,context,NULL,0,&ouResults); context = (ou=ou_name) -> ouEntry = ldap_get_first_entry(ldap,ouResults); 4. Chercher l'objectClass groupPolicyDescriptor dans l'OU de l'étape précédente - char **vals = ldap_get_values(ldap,ouEntry,"objectClass") NB: Un objet LDAP peut avoir plusieur objectClass for(i=0 ; vals[i] != NULL;i++){ if(strcmp(vals[i], "groupPolicyDescriptor")){ 4.1 Récuperer l'attribut "uri" char **vals = ldap_get_values(ldap,ouEntry,"uri"); // action system("/bin/sh <uri>") } } */ context = calloc(sizeof(char),strlen(user)+29); sprintf(context,"(&(cn=%s)(objectClass=account))",user); // 1. Récupérer l'utilisateur ret = ldap_search_s(ldap,BASE_DN,LDAP_SCOPE_SUBTREE,context,NULL,0,&userResults); userEntry = ldap_first_entry(ldap,userResults); if(userEntry){ // 2. Récupérer le(s) nom(s) de(s) l'OU (OrganizationalUnit) de l'utilisateur userVals = (char**) ldap_get_values(ldap,userEntry,"ou"); for (i = 0 ; userVals[i] != NULL ; i++ ){ context = calloc(sizeof(char),strlen(userVals[i])+40); sprintf(context,"(&(ou=%s)(objectClass=organizationalUnit))",userVals[i]); // 3. Récupérer l'OU en faisant une nouvelle recherche ret = ldap_search_s(ldap,BASE_DN,LDAP_SCOPE_SUBTREE,context,NULL,0, &ouResults); ouEntry = ldap_first_entry(ldap,ouResults); if (ouEntry){ printf("\033[33;m\nFound OU %s ... \033[00m\n", userVals[i]); printf("\033[33;m\nSearching GPO in ou=%s ... \033[00m\n", userVals[i]); ouVals = (char **) ldap_get_values(ldap,ouEntry,"objectClass"); for ( j = 0 ; ouVals[j] != NULL ; j++ ){ // 4. Chercher l'objectClass groupPolicyDescriptor dans l'OU if(strcmp(ouVals[j],"groupPolicyDescriptor") == 0){ // 4.1 Récuperer l'attribut "uri" uriVals = (char **) ldap_get_values(ldap,ouEntry,"uri"); printf("\033[33;mGPO Found in ou=%s \033[00m\n", userVals[i]); for ( k = 0 ; uriVals[k] != NULL ; k++) { printf("\033[33;mURI Script: %s\033[00m\n", uriVals[k]); } } } } else { printf("\033[33;m\nNo OU found for user: %s \033[00m\n", user ) ;} } } else { printf("\033[33;m\nUser %s not found in LDAP Directory \033[00m\n", user); } printf("\n\n----------------------------------\n"); printf("Cleaning memory\n"); printf("----------------------------------\n\n"); if(userVals) ldap_value_free(userVals); if(ouVals) ldap_value_free(ouVals); if(uriVals) ldap_value_free(uriVals); if(ouEntry) ldap_msgfree(ouEntry); if(userEntry) ldap_msgfree(userEntry); ldap_unbind(ldap); } pam_end(pamh,pamretval); return PAM_SUCCESS; }else{ printf("User not logged in.\n"); return PAM_USER_UNKNOWN; } }
CURLcode Curl_ldap(struct connectdata *conn) { CURLcode status = CURLE_OK; int rc; void *(*ldap_open)(char *, int); int (*ldap_simple_bind_s)(void *, char *, char *); int (*ldap_unbind_s)(void *); int (*ldap_url_search_s)(void *, char *, int, void **); void *(*ldap_first_entry)(void *, void *); void *(*ldap_next_entry)(void *, void *); char *(*ldap_err2string)(int); int (*ldap_entry2text)(void *, char *, void *, void *, char **, char **, int (*)(void *, char *, int), void *, char *, int, unsigned long); int (*ldap_entry2html)(void *, char *, void *, void *, char **, char **, int (*)(void *, char *, int), void *, char *, int, unsigned long, char *, char *); void *server; void *result; void *entryIterator; int ldaptext; struct SessionHandle *data=conn->data; infof(data, "LDAP: %s\n", data->change.url); DynaOpen(); if (libldap == NULL) { failf(data, "The needed LDAP library/libraries couldn't be opened"); return CURLE_LIBRARY_NOT_FOUND; } ldaptext = data->set.ftp_ascii; /* This is a dirty hack */ /* The types are needed because ANSI C distinguishes between * pointer-to-object (data) and pointer-to-function. */ DYNA_GET_FUNCTION(void *(*)(char *, int), ldap_open); DYNA_GET_FUNCTION(int (*)(void *, char *, char *), ldap_simple_bind_s); DYNA_GET_FUNCTION(int (*)(void *), ldap_unbind_s); DYNA_GET_FUNCTION(int (*)(void *, char *, int, void **), ldap_url_search_s); DYNA_GET_FUNCTION(void *(*)(void *, void *), ldap_first_entry); DYNA_GET_FUNCTION(void *(*)(void *, void *), ldap_next_entry); DYNA_GET_FUNCTION(char *(*)(int), ldap_err2string); DYNA_GET_FUNCTION(int (*)(void *, char *, void *, void *, char **, char **, int (*)(void *, char *, int), void *, char *, int, unsigned long), ldap_entry2text); DYNA_GET_FUNCTION(int (*)(void *, char *, void *, void *, char **, char **, int (*)(void *, char *, int), void *, char *, int, unsigned long, char *, char *), ldap_entry2html); server = ldap_open(conn->hostname, conn->port); if (server == NULL) { failf(data, "LDAP: Cannot connect to %s:%d", conn->hostname, conn->port); status = CURLE_COULDNT_CONNECT; } else { rc = ldap_simple_bind_s(server, conn->bits.user_passwd?data->state.user:NULL, conn->bits.user_passwd?data->state.passwd:NULL); if (rc != 0) { failf(data, "LDAP: %s", ldap_err2string(rc)); status = CURLE_LDAP_CANNOT_BIND; } else { rc = ldap_url_search_s(server, data->change.url, 0, &result); if (rc != 0) { failf(data, "LDAP: %s", ldap_err2string(rc)); status = CURLE_LDAP_SEARCH_FAILED; } else { for (entryIterator = ldap_first_entry(server, result); entryIterator; entryIterator = ldap_next_entry(server, entryIterator)) { if (ldaptext) { rc = ldap_entry2text(server, NULL, entryIterator, NULL, NULL, NULL, WriteProc, data, (char *)"", 0, 0); if (rc != 0) { failf(data, "LDAP: %s", ldap_err2string(rc)); status = CURLE_LDAP_SEARCH_FAILED; } } else { rc = ldap_entry2html(server, NULL, entryIterator, NULL, NULL, NULL, WriteProc, data, (char *)"", 0, 0, NULL, NULL); if (rc != 0) { failf(data, "LDAP: %s", ldap_err2string(rc)); status = CURLE_LDAP_SEARCH_FAILED; } } } } ldap_unbind_s(server); } } DynaClose(); /* no data to transfer */ Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return status; }
#include <stdio.h> #include <ctype.h> #include <string.h> #ifdef MACOS #include <stdlib.h> #ifdef THINK_C #include <console.h> #include <unix.h> #include <fcntl.h> #endif /* THINK_C */ #include "macos.h" #else /* MACOS */ #if defined( DOS ) || defined( _WIN32 ) #ifdef DOS #include "msdos.h" #endif #if defined( WINSOCK ) || defined( _WIN32 ) #include "console.h" #endif /* WINSOCK */ #else /* DOS */ #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/file.h> #ifndef VMS #include <fcntl.h> #include <unistd.h> #endif /* VMS */ #endif /* DOS */ #endif /* MACOS */ #include "lber.h" #include "ldap.h" #if !defined( PCNFS ) && !defined( WINSOCK ) && !defined( MACOS ) #define MOD_USE_BVALS #endif /* !PCNFS && !WINSOCK && !MACOS */ #ifdef NEEDPROTOS static void handle_result( LDAP *ld, LDAPMessage *lm ); static void print_ldap_result( LDAP *ld, LDAPMessage *lm, char *s ); static void print_search_entry( LDAP *ld, LDAPMessage *res ); static void free_list( char **list ); #else static void handle_result(); static void print_ldap_result(); static void print_search_entry(); static void free_list(); #endif /* NEEDPROTOS */ #define NOCACHEERRMSG \ "don't compile with -DNO_CACHE if you desire local caching" char *dnsuffix; #ifndef WINSOCK static char * getline( char *line, int len, FILE *fp, char *prompt ) { printf(prompt); if ( fgets( line, len, fp ) == NULL ) return( NULL ); line[ strlen( line ) - 1 ] = '\0'; return( line ); } #endif /* WINSOCK */ static char ** get_list( char *prompt ) { static char buf[256]; int num; char **result; num = 0; result = (char **) 0; while ( 1 ) { getline( buf, sizeof(buf), stdin, prompt ); if ( *buf == '\0' ) break; if ( result == (char **) 0 ) result = (char **) malloc( sizeof(char *) ); else result = (char **) realloc( result, sizeof(char *) * (num + 1) ); result[num++] = (char *) strdup( buf ); } if ( result == (char **) 0 ) return( NULL ); result = (char **) realloc( result, sizeof(char *) * (num + 1) ); result[num] = NULL; return( result ); } static void free_list( char **list ) { int i; if ( list != NULL ) { for ( i = 0; list[ i ] != NULL; ++i ) { free( list[ i ] ); } free( (char *)list ); } } #ifdef MOD_USE_BVALS static int file_read( char *path, struct berval *bv ) { FILE *fp; long rlen; int eof; if (( fp = fopen( path, "r" )) == NULL ) { perror( path ); return( -1 ); } if ( fseek( fp, 0L, SEEK_END ) != 0 ) { perror( path ); fclose( fp ); return( -1 ); } bv->bv_len = ftell( fp ); if (( bv->bv_val = (char *)malloc( bv->bv_len )) == NULL ) { perror( "malloc" ); fclose( fp ); return( -1 ); } if ( fseek( fp, 0L, SEEK_SET ) != 0 ) { perror( path ); fclose( fp ); return( -1 ); } rlen = fread( bv->bv_val, 1, bv->bv_len, fp ); eof = feof( fp ); fclose( fp ); if ( rlen != bv->bv_len ) { perror( path ); free( bv->bv_val ); return( -1 ); } return( bv->bv_len ); } #endif /* MOD_USE_BVALS */ static LDAPMod ** get_modlist( char *prompt1, char *prompt2, char *prompt3 ) { static char buf[256]; int num; LDAPMod tmp; LDAPMod **result; #ifdef MOD_USE_BVALS struct berval **bvals; #endif /* MOD_USE_BVALS */ num = 0; result = NULL; while ( 1 ) { if ( prompt1 ) { getline( buf, sizeof(buf), stdin, prompt1 ); tmp.mod_op = atoi( buf ); if ( tmp.mod_op == -1 || buf[0] == '\0' ) break; } getline( buf, sizeof(buf), stdin, prompt2 ); if ( buf[0] == '\0' ) break; tmp.mod_type = strdup( buf ); tmp.mod_values = get_list( prompt3 ); #ifdef MOD_USE_BVALS if ( tmp.mod_values != NULL ) { int i; for ( i = 0; tmp.mod_values[i] != NULL; ++i ) ; bvals = (struct berval **)calloc( i + 1, sizeof( struct berval *)); for ( i = 0; tmp.mod_values[i] != NULL; ++i ) { bvals[i] = (struct berval *)malloc( sizeof( struct berval )); if ( strncmp( tmp.mod_values[i], "{FILE}", 6 ) == 0 ) { if ( file_read( tmp.mod_values[i] + 6, bvals[i] ) < 0 ) { return( NULL ); } } else { bvals[i]->bv_val = tmp.mod_values[i]; bvals[i]->bv_len = strlen( tmp.mod_values[i] ); } } tmp.mod_bvalues = bvals; tmp.mod_op |= LDAP_MOD_BVALUES; } #endif /* MOD_USE_BVALS */ if ( result == NULL ) result = (LDAPMod **) malloc( sizeof(LDAPMod *) ); else result = (LDAPMod **) realloc( result, sizeof(LDAPMod *) * (num + 1) ); result[num] = (LDAPMod *) malloc( sizeof(LDAPMod) ); *(result[num]) = tmp; /* struct copy */ num++; } if ( result == NULL ) return( NULL ); result = (LDAPMod **) realloc( result, sizeof(LDAPMod *) * (num + 1) ); result[num] = NULL; return( result ); } #ifdef LDAP_REFERRALS int bind_prompt( LDAP *ld, char **dnp, char **passwdp, int *authmethodp, int freeit ) { static char dn[256], passwd[256]; if ( !freeit ) { #ifdef KERBEROS getline( dn, sizeof(dn), stdin, "re-bind method (0->simple, " "1->krbv41, 2->krbv42, 3->krbv41&2)? " ); if (( *authmethodp = atoi( dn )) == 3 ) { *authmethodp = LDAP_AUTH_KRBV4; } else { *authmethodp |= 0x80; } #else /* KERBEROS */ *authmethodp = LDAP_AUTH_SIMPLE; #endif /* KERBEROS */ getline( dn, sizeof(dn), stdin, "re-bind dn? " ); strcat( dn, dnsuffix ); *dnp = dn; if ( *authmethodp == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) { getline( passwd, sizeof(passwd), stdin, "re-bind password? " ); } else { passwd[0] = '\0'; } *passwdp = passwd; } return( LDAP_SUCCESS ); } #endif /* LDAP_REFERRALS */ int #ifdef WINSOCK ldapmain( #else /* WINSOCK */ main( #endif /* WINSOCK */ int argc, char **argv ) { LDAP *ld; int i, c, port, cldapflg, 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; 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; extern char *optarg; extern int optind; #ifdef MACOS if (( argv = get_list( "cmd line arg?" )) == NULL ) { exit( 1 ); } for ( argc = 0; argv[ argc ] != NULL; ++argc ) { ; } #endif /* MACOS */ host = NULL; port = LDAP_PORT; dnsuffix = ""; cldapflg = errflg = 0; while (( c = getopt( argc, argv, "uh:d:s:p:t:T:" )) != -1 ) { switch( c ) { case 'u': #ifdef CLDAP cldapflg++; #else /* CLDAP */ printf( "Compile with -DCLDAP for UDP support\n" ); #endif /* CLDAP */ break; case 'd': #ifdef LDAP_DEBUG ldap_debug = atoi( optarg ); if ( ldap_debug & LDAP_DEBUG_PACKETS ) { lber_debug = ldap_debug; } #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; #if !defined(MACOS) && !defined(DOS) 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; #endif default: ++errflg; } } if ( host == NULL && optind == argc - 1 ) { host = argv[ optind ]; ++optind; } if ( errflg || optind < argc - 1 ) { fprintf( stderr, usage, argv[ 0 ] ); exit( 1 ); } printf( "%sldap_open( %s, %d )\n", cldapflg ? "c" : "", host == NULL ? "(null)" : host, port ); if ( cldapflg ) { #ifdef CLDAP ld = cldap_open( host, port ); #endif /* CLDAP */ } else { ld = ldap_open( host, port ); } if ( ld == NULL ) { perror( "ldap_open" ); exit(1); } #if !defined(MACOS) && !defined(DOS) if ( copyfname != NULL ) { if ( (ld->ld_sb.sb_fd = open( copyfname, O_WRONLY | O_CREAT, 0600 )) == -1 ) { perror( copyfname ); exit ( 1 ); } ld->ld_sb.sb_options = copyoptions; } #endif bound = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; (void) memset( line, '\0', sizeof(line) ); while ( getline( 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 */ getline( 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 */ getline( 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 */ #ifdef KERBEROS getline( line, sizeof(line), stdin, "method (0->simple, 1->krbv41, 2->krbv42)? " ); method = atoi( line ) | 0x80; #else /* KERBEROS */ method = LDAP_AUTH_SIMPLE; #endif /* KERBEROS */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( method == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) getline( 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 */ #ifdef KERBEROS getline( line, sizeof(line), stdin, "method 0->simple 1->krbv41 2->krbv42 3->krb? " ); method = atoi( line ); if ( method == 3 ) method = LDAP_AUTH_KRBV4; else method = method | 0x80; #else /* KERBEROS */ method = LDAP_AUTH_SIMPLE; #endif /* KERBEROS */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( dn[0] != '\0' ) getline( 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 */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); getline( attr, sizeof(attr), stdin, "attr? " ); getline( 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 getline( line, sizeof(line), stdin, "debug level? " ); ldap_debug = atoi( line ); if ( ldap_debug & LDAP_DEBUG_PACKETS ) { lber_debug = ldap_debug; } #else printf( "Compile with -DLDAP_DEBUG for debugging\n" ); #endif break; case 'E': /* explode a dn */ getline( 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 */ getline( line, sizeof(line), stdin, "msgid? " ); ld->ld_msgid = atoi( line ); break; case 'v': /* set version number */ getline( line, sizeof(line), stdin, "version? " ); ld->ld_version = atoi( line ); break; case 'm': /* modify or modifyrdn */ if ( strncmp( line, "modify", 4 ) == 0 ) { getline( 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 ) { getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); getline( 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 */ #ifdef CLDAP if ( cldapflg ) cldap_close( ld ); #endif /* CLDAP */ #ifdef LDAP_REFERRALS if ( !cldapflg ) #else /* LDAP_REFERRALS */ if ( !cldapflg && bound ) #endif /* LDAP_REFERRALS */ ldap_unbind( ld ); exit( 0 ); break; case 'r': /* result or remove */ switch ( command3 ) { case 's': /* result */ getline( line, sizeof(line), stdin, "msgid (-1=>any)? " ); if ( line[0] == '\0' ) id = -1; else id = atoi( line ); getline( 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 = NULLMSG; break; case 'm': /* remove */ getline( 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 */ getline( dn, sizeof(dn), stdin, "searchbase? " ); strcat( dn, dnsuffix ); getline( line, sizeof(line), stdin, "scope (0=Base, 1=One Level, 2=Subtree)? " ); scope = atoi( line ); getline( filter, sizeof(filter), stdin, "search filter (e.g. sn=jones)? " ); types = get_list( "attrs to return? " ); getline( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); if ( cldapflg ) { #ifdef CLDAP getline( line, sizeof(line), stdin, "Requestor DN (for logging)? " ); if ( cldap_search_s( ld, dn, scope, filter, types, attrsonly, &res, line ) != 0 ) { ldap_perror( ld, "cldap_search_s" ); } else { printf( "\nresult: msgid %d\n", res->lm_msgid ); handle_result( ld, res ); res = NULLMSG; } #endif /* CLDAP */ } else { 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 */ getline( line, sizeof(line), stdin, "timeout? " ); timeout.tv_sec = atoi( line ); break; case 'U': /* set ufn search prefix */ getline( line, sizeof(line), stdin, "ufn prefix? " ); ldap_ufn_setprefix( ld, line ); break; case 'u': /* user friendly search w/optional timeout */ getline( dn, sizeof(dn), stdin, "ufn? " ); strcat( dn, dnsuffix ); types = get_list( "attrs to return? " ); getline( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); if ( command2 == 't' ) { id = ldap_ufn_search_c( ld, dn, types, attrsonly, &res, ldap_ufn_timeout, &timeout ); } else { id = ldap_ufn_search_s( ld, dn, types, attrsonly, &res ); } if ( res == NULL ) ldap_perror( ld, "ldap_ufn_search" ); else { printf( "\nresult: err %d\n", id ); handle_result( ld, res ); res = NULLMSG; } free_list( types ); break; case 'l': /* URL search */ getline( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); getline( line, sizeof(line), stdin, "LDAP URL? " ); if (( id = ldap_url_search( ld, line, attrsonly )) == -1 ) { ldap_perror( ld, "ldap_url_search" ); } else { printf( "URL search initiated with id %d\n", id ); } break; case 'p': /* parse LDAP URL */ getline( 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_ONELEVEL ? "ONE" : ludp->lud_scope == LDAP_SCOPE_BASE ? "BASE" : ludp->lud_scope == LDAP_SCOPE_SUBTREE ? "SUB" : "**invalid**" ); printf( "\tfilter: <%s>\n", ludp->lud_filter ); ldap_free_urldesc( ludp ); } break; case 'n': /* set dn suffix, for convenience */ getline( line, sizeof(line), stdin, "DN suffix? " ); strcpy( dnsuffix, line ); break; case 'e': /* enable cache */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "Cache timeout (secs)? " ); i = atoi( line ); getline( line, sizeof(line), stdin, "Maximum memory to use (bytes)? " ); if ( ldap_enable_cache( ld, i, atoi( line )) == 0 ) { printf( "local cache is on\n" ); } else { printf( "ldap_enable_cache failed\n" ); } #endif /* NO_CACHE */ break; case 'x': /* uncache entry */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "DN? " ); ldap_uncache_entry( ld, line ); #endif /* NO_CACHE */ break; case 'X': /* uncache request */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "request msgid? " ); ldap_uncache_request( ld, atoi( line )); #endif /* NO_CACHE */ break; case 'o': /* set ldap options */ getline( line, sizeof(line), stdin, "alias deref (0=never, 1=searching, 2" "=finding, 3=always)?" ); ld->ld_deref = atoi( line ); getline( line, sizeof(line), stdin, "timelimit?" ); ld->ld_timelimit = atoi( line ); getline( line, sizeof(line), stdin, "sizelimit?" ); ld->ld_sizelimit = atoi( line ); ld->ld_options = 0; #ifdef STR_TRANSLATION getline( line, sizeof(line), stdin, "Automatic translation of T.61 strings " "(0=no, 1=yes)?" ); if ( atoi( line ) == 0 ) { ld->ld_lberoptions &= ~LBER_TRANSLATE_STRINGS; } else { ld->ld_lberoptions |= LBER_TRANSLATE_STRINGS; #ifdef LDAP_CHARSET_8859 getline( line, sizeof(line), stdin, "Translate to/from ISO-8859 " "(0=no, 1=yes?" ); if ( atoi( line ) != 0 ) { ldap_set_string_translators( ld, ldap_8859_to_t61, ldap_t61_to_8859 ); } #endif /* LDAP_CHARSET_8859 */ } #endif /* STR_TRANSLATION */ #ifdef LDAP_DNS getline( line, sizeof(line), stdin, "Use DN & DNS to determine where to send " "requests (0=no, 1=yes)?" ); if ( atoi( line ) != 0 ) { ld->ld_options |= LDAP_OPT_DNS; } #endif /* LDAP_DNS */ #ifdef LDAP_REFERRALS getline( line, sizeof(line), stdin, "Recognize and chase referrals (0=no, 1=yes)?"); if ( atoi( line ) != 0 ) { ld->ld_options |= LDAP_OPT_REFERRALS; getline( 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 ); } } #endif /* LDAP_REFERRALS */ break; case 'O': /* set cache options */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "cache errors (0=smart, 1=never, 2=always)?" ); switch( atoi( line )) { case 0: ldap_set_cache_options( ld, 0 ); break; case 1: ldap_set_cache_options( ld, LDAP_CACHE_OPT_CACHENOERRS ); break; case 2: ldap_set_cache_options( ld, LDAP_CACHE_OPT_CACHEALLERRS ); break; default: printf( "not a valid cache option\n" ); } #endif /* NO_CACHE */ break; case '?': /* help */ printf( "Commands: [ad]d [ab]andon [b]ind\n" ); printf( " [B]ind async [c]ompare [l]URL search\n" ); printf( " [modi]fy [modr]dn [rem]ove\n" ); printf( " [res]ult [s]earch [q]uit/unbind\n\n" ); printf( " [u]fn search [ut]fn search with timeout\n" ); printf( " [d]ebug [e]nable cache set ms[g]id\n" ); printf( " d[n]suffix [t]imeout [v]ersion\n" ); printf( " [U]fn prefix [x]uncache entry [X]uncache request\n" ); printf( " [?]help [o]ptions [O]cache options\n" ); printf( " [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 ); }
int main(int argc, char* argv[]) { DWORD dwError = 0; const int ldapVer = LDAP_VERSION3; PVMDIR_QUERY_ARGS pArgs = NULL; PSTR pszLdapURL = NULL; LDAP* pLd = NULL; BerValue ldapBindPwd = {0}; LDAPMessage* pResult = NULL; PSTR pszDN = NULL; dwError = VmDirQueryParseArgs(argc, argv, &pArgs); BAIL_ON_VMDIR_ERROR(dwError); dwError = VmDirAllocateStringAVsnprintf( &pszLdapURL, "ldap://%s", pArgs->pszHostname); BAIL_ON_VMDIR_ERROR(dwError); #if 0 dwError = ldap_initialize(&pLd, pszLdapURL); BAIL_ON_VMDIR_ERROR(dwError); #else pLd = ldap_open(pArgs->pszHostname, 389); if (!pLd) { dwError = VMDIR_ERROR_SERVER_DOWN; BAIL_ON_VMDIR_ERROR(dwError); } #endif dwError = ldap_set_option(pLd, LDAP_OPT_PROTOCOL_VERSION, &ldapVer); BAIL_ON_VMDIR_ERROR(dwError); dwError = ldap_set_option(pLd, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); BAIL_ON_VMDIR_ERROR(dwError); ldapBindPwd.bv_val = pArgs->pszPassword; ldapBindPwd.bv_len = strlen(pArgs->pszPassword); #if 0 dwError = ldap_sasl_bind_s( pLd, pArgs->pszBindDN, LDAP_SASL_SIMPLE, &ldapBindPwd, NULL, NULL, NULL); BAIL_ON_VMDIR_ERROR(dwError); #else dwError = ldap_bind_s( pLd, pArgs->pszBindDN, pArgs->pszPassword, LDAP_AUTH_SIMPLE); BAIL_ON_VMDIR_ERROR(dwError); #endif #if 0 dwError = ldap_search_ext_s( pLd, pArgs->pszBaseDN, LDAP_SCOPE_SUBTREE, pArgs->pszFilter, NULL, TRUE, NULL, // server ctrls NULL, // client ctrls NULL, // timeout -1, // size limit, &pResult); BAIL_ON_VMDIR_ERROR(dwError); #else dwError = ldap_search_s( pLd, pArgs->pszBaseDN, LDAP_SCOPE_SUBTREE, pArgs->pszFilter, NULL, TRUE, &pResult); BAIL_ON_VMDIR_ERROR(dwError); #endif if (ldap_count_entries(pLd, pResult) > 0) { LDAPMessage* pEntry = ldap_first_entry(pLd, pResult); for (; pEntry != NULL; pEntry = ldap_next_entry(pLd, pEntry)) { if (pszDN) { ldap_memfree(pszDN); pszDN = NULL; } pszDN = ldap_get_dn(pLd, pEntry); if (IsNullOrEmptyString(pszDN)) { dwError = VMDIR_ERROR_INVALID_DN; BAIL_ON_VMDIR_ERROR(dwError); } fprintf(stdout, "DN : %s\n", pszDN); } } cleanup: if (pArgs) { VmDirFreeArgs(pArgs); } VMDIR_SAFE_FREE_MEMORY(pszLdapURL); if (pResult) { ldap_msgfree(pResult); } if (pszDN) { ldap_memfree(pszDN); } if (pLd) { ldap_unbind_ext_s(pLd, NULL, NULL); } return dwError; error: goto cleanup; }
int check_challenge(scep_t *scep) { X509_REQ *req; char *challenge, *dn; X509_NAME *subject; LDAP *ldap = NULL; /* the clientreq field in the scep structure contains the */ /* request, even for getcertinitial messages where the request */ /* does not contain the data originally sent with the request */ req = scep->clientreq; if (debug) BIO_printf(bio_err, "%s:%d: checking challenge password in " "request %p\n", __FILE__, __LINE__, req); /* check whether is at all challenge password in the request */ if (NULL == (challenge = get_challenge(scep))) { BIO_printf(bio_err, "%s:%d: no challenge password found\n", __FILE__, __LINE__); goto err; } if (debug) BIO_printf(bio_err, "%s:%d: challenge Password '%s'\n", __FILE__, __LINE__, challenge); /* a challenge password of zero length is not authenticable */ if (strlen(challenge) == 0) { if (debug) BIO_printf(bio_err, "%s:%d: zero challenge\n", __FILE__, __LINE__); goto err; } /* get the client distinguished name */ subject = X509_REQ_get_subject_name(req); if (debug) { char name[1024]; X509_NAME_oneline(subject, name, sizeof(name)); BIO_printf(bio_err, "%s:%d: requestor: %s\n", __FILE__, __LINE__, name); } /* map to a suitable LDAP distinguished name */ dn = x509_to_ldap(scep, subject); if (debug) BIO_printf(bio_err, "%s:%d: mapped requestor to LDAP DN '%s'\n", __FILE__, __LINE__, dn); /* connect to the ldap directory */ ldap = ldap_open(scep->l.ldaphost, scep->l.ldapport); if (ldap == NULL) { BIO_printf(bio_err, "%s:%d: cannot connect to %s:%d\n", __FILE__, __LINE__, scep->l.ldaphost, scep->l.ldapport); goto err; } /* authenticate the LDAP DN in the directory */ if (ldap_simple_bind_s(ldap, dn, challenge) != LDAP_SUCCESS && 0) { BIO_printf(bio_err, "%s:%d: cannot ldap_simple_bind_s\n", __FILE__, __LINE__); syslog(LOG_ERR, "LDAP authentication for %s failed", dn); goto err; } /* clean up any ldap connection */ ldap_unbind(ldap); /* if we get to this point, then authentication was successful */ BIO_printf(bio_err, "%s:%d: check successful\n", __FILE__, __LINE__); return 0; err: /* XXX should do some cleanup here to prevent memory leaks */ if (ldap) ldap_unbind(ldap); ERR_print_errors(bio_err); return -1; }
/* * Do an LDAP lookup to the server described in the info argument. * * Args info -- LDAP info for server. * string -- String to lookup. * cust -- Possible custom filter description. * wp_err -- We set this is we get a white pages error. * name_in_error -- Caller sets this if they want us to include the server * name in error messages. * * Returns Results of lookup, NULL if lookup failed. */ LDAP_SERV_RES_S * ldap_lookup(LDAP_SERV_S *info, char *string, CUSTOM_FILT_S *cust, WP_ERR_S *wp_err, int name_in_error) { char ebuf[900]; char buf[900]; char *serv, *base, *serv_errstr; char *mailattr, *snattr, *gnattr, *cnattr; int we_cancel = 0, we_turned_on = 0; LDAP_SERV_RES_S *serv_res = NULL; LDAP *ld; long pwdtrial = 0L; int ld_errnum; char *ld_errstr; if(!info) return(serv_res); serv = cpystr((info->serv && *info->serv) ? info->serv : "?"); if(name_in_error) snprintf(ebuf, sizeof(ebuf), " (%s)", (info->nick && *info->nick) ? info->nick : serv); else ebuf[0] = '\0'; serv_errstr = cpystr(ebuf); base = cpystr(info->base ? info->base : ""); if(info->port < 0) info->port = LDAP_PORT; if(info->type < 0) info->type = DEF_LDAP_TYPE; if(info->srch < 0) info->srch = DEF_LDAP_SRCH; if(info->time < 0) info->time = DEF_LDAP_TIME; if(info->size < 0) info->size = DEF_LDAP_SIZE; if(info->scope < 0) info->scope = DEF_LDAP_SCOPE; mailattr = (info->mailattr && info->mailattr[0]) ? info->mailattr : DEF_LDAP_MAILATTR; snattr = (info->snattr && info->snattr[0]) ? info->snattr : DEF_LDAP_SNATTR; gnattr = (info->gnattr && info->gnattr[0]) ? info->gnattr : DEF_LDAP_GNATTR; cnattr = (info->cnattr && info->cnattr[0]) ? info->cnattr : DEF_LDAP_CNATTR; /* * We may want to keep ldap handles open, but at least for * now, re-open them every time. */ dprint((3, "ldap_lookup(%s,%d)\n", serv ? serv : "?", info->port)); snprintf(ebuf, sizeof(ebuf), "Searching%s%s%s on %s", (string && *string) ? " for \"" : "", (string && *string) ? string : "", (string && *string) ? "\"" : "", serv); we_turned_on = intr_handling_on(); /* this erases keymenu */ we_cancel = busy_cue(ebuf, NULL, 0); if(wp_err->mangled) *(wp_err->mangled) = 1; #ifdef _SOLARIS_SDK if(info->tls || info->tlsmust) ldapssl_client_init(NULL, NULL); if((ld = ldap_init(serv, info->port)) == NULL) #else #if (LDAPAPI >= 11) if((ld = ldap_init(serv, info->port)) == NULL) #else if((ld = ldap_open(serv, info->port)) == NULL) #endif #endif { /* TRANSLATORS: All of the three args together are an error message */ snprintf(ebuf, sizeof(ebuf), _("Access to LDAP server failed: %s%s(%s)"), errno ? error_description(errno) : "", errno ? " " : "", serv); wp_err->wp_err_occurred = 1; if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); } else if(!ps_global->intr_pending){ int proto = 3, tlsmustbail = 0; char pwd[NETMAXPASSWD], user[NETMAXUSER]; char *passwd = NULL; char hostbuf[1024]; NETMBX mb; #ifndef _WINDOWS int rc; #endif memset(&mb, 0, sizeof(mb)); #ifdef _SOLARIS_SDK if(info->tls || info->tlsmust) rc = ldapssl_install_routines(ld); #endif if(ldap_v3_is_supported(ld) && our_ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &proto) == 0){ dprint((5, "ldap: using version 3 protocol\n")); } /* * If we don't set RESTART then the select() waiting for the answer * in libldap will be interrupted and stopped by our busy_cue. */ our_ldap_set_option(ld, LDAP_OPT_RESTART, LDAP_OPT_ON); /* * If we need to authenticate, get the password. We are not * supporting SASL authentication, just LDAP simple. */ if(info->binddn && info->binddn[0]){ char pmt[500]; char *space; snprintf(hostbuf, sizeof(hostbuf), "{%s}dummy", info->serv ? info->serv : "?"); /* * We don't handle multiple space-delimited hosts well. * We don't know which we're asking for a password for. * We're not connected yet so we can't know. */ if((space=strindex(hostbuf, ' ')) != NULL) *space = '\0'; mail_valid_net_parse_work(hostbuf, &mb, "ldap"); mb.port = info->port; mb.tlsflag = (info->tls || info->tlsmust) ? 1 : 0; try_password_again: if(mb.tlsflag && (pwdtrial > 0 || #ifndef _WINDOWS #ifdef _SOLARIS_SDK (rc == LDAP_SUCCESS) #else /* !_SOLARIS_SDK */ ((rc=ldap_start_tls_s(ld, NULL, NULL)) == LDAP_SUCCESS) #endif /* !_SOLARIS_SDK */ #else /* _WINDOWS */ 0 /* TODO: find a way to do this in Windows */ #endif /* _WINDOWS */ )) mb.tlsflag = 1; else mb.tlsflag = 0; if((info->tls || info->tlsmust) && !mb.tlsflag){ q_status_message(SM_ORDER, 3, 5, "Not able to start TLS encryption for LDAP server"); if(info->tlsmust) tlsmustbail++; } if(!tlsmustbail){ snprintf(pmt, sizeof(pmt), " %s", (info->nick && *info->nick) ? info->nick : serv); mm_login_work(&mb, user, pwd, pwdtrial, pmt, info->binddn); if(pwd && pwd[0]) passwd = pwd; } } /* * LDAPv2 requires the bind. v3 doesn't require it but we want * to tell the server we're v3 if the server supports v3, and if the * server doesn't support v3 the bind is required. */ if(tlsmustbail || ldap_simple_bind_s(ld, info->binddn, passwd) != LDAP_SUCCESS){ wp_err->wp_err_occurred = 1; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); if(!tlsmustbail && info->binddn && info->binddn[0] && pwdtrial < 2L && ld_errnum == LDAP_INVALID_CREDENTIALS){ pwdtrial++; q_status_message(SM_ORDER, 3, 5, _("Invalid password")); goto try_password_again; } snprintf(ebuf, sizeof(ebuf), _("LDAP server failed: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); if(wp_err->error) fs_give((void **)&wp_err->error); if(we_cancel) cancel_busy_cue(-1); ldap_unbind(ld); wp_err->error = cpystr(ebuf); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); } else if(!ps_global->intr_pending){ int srch_res, args, slen, flen; #define TEMPLATELEN 512 char filt_template[TEMPLATELEN + 1]; char filt_format[2*TEMPLATELEN + 1]; char filter[2*TEMPLATELEN + 1]; char scp[2*TEMPLATELEN + 1]; char *p, *q; LDAPMessage *res = NULL; int intr_happened = 0; int tl; tl = (info->time == 0) ? info->time : info->time + 10; our_ldap_set_option(ld, LDAP_OPT_TIMELIMIT, &tl); our_ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &info->size); /* * If a custom filter has been passed in and it doesn't include a * request to combine it with the configured filter, then replace * any configured filter with the passed in filter. */ if(cust && cust->filt && !cust->combine){ if(info->cust) fs_give((void **)&info->cust); info->cust = cpystr(cust->filt); } if(info->cust && *info->cust){ /* use custom filter if present */ strncpy(filt_template, info->cust, sizeof(filt_template)); filt_template[sizeof(filt_template)-1] = '\0'; } else{ /* else use configured filter */ switch(info->type){ case LDAP_TYPE_SUR: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", snattr); break; case LDAP_TYPE_GIVEN: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", gnattr); break; case LDAP_TYPE_EMAIL: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", mailattr); break; case LDAP_TYPE_CN_EMAIL: snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s))", cnattr, mailattr); break; case LDAP_TYPE_SUR_GIVEN: snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s))", snattr, gnattr); break; case LDAP_TYPE_SEVERAL: snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s)(%s=%%s)(%s=%%s))", cnattr, mailattr, snattr, gnattr); break; default: case LDAP_TYPE_CN: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", cnattr); break; } } /* just copy if custom */ if(info->cust && *info->cust) info->srch = LDAP_SRCH_EQUALS; p = filt_template; q = filt_format; memset((void *)filt_format, 0, sizeof(filt_format)); args = 0; while(*p && (q - filt_format) + 4 < sizeof(filt_format)){ if(*p == '%' && *(p+1) == 's'){ args++; switch(info->srch){ /* Exact match */ case LDAP_SRCH_EQUALS: *q++ = *p++; *q++ = *p++; break; /* Append wildcard after %s */ case LDAP_SRCH_BEGINS: *q++ = *p++; *q++ = *p++; *q++ = '*'; break; /* Insert wildcard before %s */ case LDAP_SRCH_ENDS: *q++ = '*'; *q++ = *p++; *q++ = *p++; break; /* Put wildcard before and after %s */ default: case LDAP_SRCH_CONTAINS: *q++ = '*'; *q++ = *p++; *q++ = *p++; *q++ = '*'; break; } } else *q++ = *p++; } if(q - filt_format < sizeof(filt_format)) *q = '\0'; filt_format[sizeof(filt_format)-1] = '\0'; /* * If combine is lit we put the custom filter and the filt_format * filter and combine them with an &. */ if(cust && cust->filt && cust->combine){ char *combined; size_t l; l = strlen(filt_format) + strlen(cust->filt) + 3; combined = (char *) fs_get((l+1) * sizeof(char)); snprintf(combined, l+1, "(&%s%s)", cust->filt, filt_format); strncpy(filt_format, combined, sizeof(filt_format)); filt_format[sizeof(filt_format)-1] = '\0'; fs_give((void **) &combined); } /* * Ad hoc attempt to make "Steve Hubert" match * Steven Hubert but not Steven Shubert. * We replace a <SPACE> with * <SPACE> (not * <SPACE> *). */ memset((void *)scp, 0, sizeof(scp)); if(info->nosub) strncpy(scp, string, sizeof(scp)); else{ p = string; q = scp; while(*p && (q - scp) + 1 < sizeof(scp)){ if(*p == SPACE && *(p+1) != SPACE){ *q++ = '*'; *q++ = *p++; } else *q++ = *p++; } } scp[sizeof(scp)-1] = '\0'; slen = strlen(scp); flen = strlen(filt_format); /* truncate string if it will overflow filter */ if(args*slen + flen - 2*args > sizeof(filter)-1) scp[(sizeof(filter)-1 - flen)/args] = '\0'; /* * Replace %s's with scp. */ switch(args){ case 0: snprintf(filter, sizeof(filter), "%s", filt_format); break; case 1: snprintf(filter, sizeof(filter), filt_format, scp); break; case 2: snprintf(filter, sizeof(filter), filt_format, scp, scp); break; case 3: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp); break; case 4: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp); break; case 5: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp); break; case 6: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp); break; case 7: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp); break; case 8: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp, scp); break; case 9: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp, scp, scp); break; case 10: default: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp, scp, scp, scp); break; } /* replace double *'s with single *'s in filter */ for(p = q = filter; *p; p++) if(*p != '*' || p == filter || *(p-1) != '*') *q++ = *p; *q = '\0'; (void) removing_double_quotes(base); dprint((5, "about to ldap_search(\"%s\", %s)\n", base ? base : "?", filter ? filter : "?")); if(ps_global->intr_pending) srch_res = LDAP_PROTOCOL_ERROR; else{ int msgid; time_t start_time; start_time = time((time_t *)0); dprint((6, "ldap_lookup: calling ldap_search\n")); msgid = ldap_search(ld, base, info->scope, filter, NULL, 0); if(msgid == -1) srch_res = our_ldap_get_lderrno(ld, NULL, NULL); else{ int lres; /* * Warning: struct timeval is not portable. However, since it is * part of LDAP api it must be portable to all platforms LDAP * has been ported to. */ struct timeval t; t.tv_sec = 1; t.tv_usec = 0; do { if(ps_global->intr_pending) intr_happened = 1; dprint((6, "ldap_result(id=%d): ", msgid)); if((lres=ldap_result(ld, msgid, LDAP_MSG_ALL, &t, &res)) == -1){ /* error */ srch_res = our_ldap_get_lderrno(ld, NULL, NULL); dprint((6, "error (-1 returned): ld_errno=%d\n", srch_res)); } else if(lres == 0){ /* timeout, no results available */ if(intr_happened){ ldap_abandon(ld, msgid); srch_res = LDAP_PROTOCOL_ERROR; if(our_ldap_get_lderrno(ld, NULL, NULL) == LDAP_SUCCESS) our_ldap_set_lderrno(ld, LDAP_PROTOCOL_ERROR, NULL, NULL); dprint((6, "timeout, intr: srch_res=%d\n", srch_res)); } else if(info->time > 0 && ((long)time((time_t *)0) - start_time) > info->time){ /* try for partial results */ t.tv_sec = 0; t.tv_usec = 0; lres = ldap_result(ld, msgid, LDAP_MSG_RECEIVED, &t, &res); if(lres > 0 && lres != LDAP_RES_SEARCH_RESULT){ srch_res = LDAP_SUCCESS; dprint((6, "partial result: lres=0x%x\n", lres)); } else{ if(lres == 0) ldap_abandon(ld, msgid); srch_res = LDAP_TIMEOUT; if(our_ldap_get_lderrno(ld, NULL, NULL) == LDAP_SUCCESS) our_ldap_set_lderrno(ld, LDAP_TIMEOUT, NULL, NULL); dprint((6, "timeout, total_time (%d), srch_res=%d\n", info->time, srch_res)); } } else{ dprint((6, "timeout\n")); } } else{ srch_res = ldap_result2error(ld, res, 0); dprint((6, "lres=0x%x, srch_res=%d\n", lres, srch_res)); } }while(lres == 0 && !(intr_happened || (info->time > 0 && ((long)time((time_t *)0) - start_time) > info->time))); } } if(intr_happened){ wp_exit = 1; if(we_cancel) cancel_busy_cue(-1); if(wp_err->error) fs_give((void **)&wp_err->error); else{ q_status_message(SM_ORDER, 0, 1, "Interrupt"); display_message('x'); fflush(stdout); } if(res) ldap_msgfree(res); if(ld) ldap_unbind(ld); res = NULL; ld = NULL; } else if(srch_res != LDAP_SUCCESS && srch_res != LDAP_TIMELIMIT_EXCEEDED && srch_res != LDAP_RESULTS_TOO_LARGE && srch_res != LDAP_TIMEOUT && srch_res != LDAP_SIZELIMIT_EXCEEDED){ wp_err->wp_err_occurred = 1; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); snprintf(ebuf, sizeof(ebuf), _("LDAP search failed: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); if(res) ldap_msgfree(res); if(ld) ldap_unbind(ld); res = NULL; ld = NULL; } else{ int cnt; cnt = ldap_count_entries(ld, res); if(cnt > 0){ if(srch_res == LDAP_TIMELIMIT_EXCEEDED || srch_res == LDAP_RESULTS_TOO_LARGE || srch_res == LDAP_TIMEOUT || srch_res == LDAP_SIZELIMIT_EXCEEDED){ wp_err->wp_err_occurred = 1; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); snprintf(ebuf, sizeof(ebuf), _("LDAP partial results: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); dprint((2, "%s\n", ebuf)); if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); } dprint((5, "Matched %d entries on %s\n", cnt, serv ? serv : "?")); serv_res = (LDAP_SERV_RES_S *)fs_get(sizeof(LDAP_SERV_RES_S)); memset((void *)serv_res, 0, sizeof(*serv_res)); serv_res->ld = ld; serv_res->res = res; serv_res->info_used = copy_ldap_serv_info(info); /* Save by reference? */ if(info->ref){ snprintf(buf, sizeof(buf), "%s:%s", serv, comatose(info->port)); serv_res->serv = cpystr(buf); } else serv_res->serv = NULL; serv_res->next = NULL; } else{ if(srch_res == LDAP_TIMELIMIT_EXCEEDED || srch_res == LDAP_RESULTS_TOO_LARGE || srch_res == LDAP_TIMEOUT || srch_res == LDAP_SIZELIMIT_EXCEEDED){ wp_err->wp_err_occurred = 1; wp_err->ldap_errno = srch_res; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); snprintf(ebuf, sizeof(ebuf), _("LDAP search failed: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); } dprint((5, "Matched 0 entries on %s\n", serv ? serv : "?")); if(res) ldap_msgfree(res); if(ld) ldap_unbind(ld); res = NULL; ld = NULL; } } } } if(we_cancel) cancel_busy_cue(-1); if(we_turned_on) intr_handling_off(); if(serv) fs_give((void **)&serv); if(base) fs_give((void **)&base); if(serv_errstr) fs_give((void **)&serv_errstr); return(serv_res); }