/* 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 _ldap_get_home_param(void) { char *attrs[] = { NULL }; char *filter, *dn; char **values; LDAP *ld; LDAPMessage *res, *entry; int ret; ld = ldap_init(LDAP_HOST, LDAP_PORT); if (!ld) { fprintf(stderr, "%s: unable to initialise ldap connection\n", prog); return 1; } ret = ldap_simple_bind_s(ld, LDAP_BIND_DN, LDAP_BIND_PASSWD); if (ret) return 1; filter = malloc(sizeof(LDAP_FILTER) + strlen(user) + strlen(host)); sprintf(filter, LDAP_FILTER, user, host); ret = ldap_search_s(ld, LDAP_BASE, LDAP_SCOPE, filter, attrs, 0, &res); if (ret) { fprintf(stderr, "%s: ldap search failed: %s\n", prog, ldap_err2string(ret)); return 1; } entry = ldap_first_entry(ld, res); if (!entry) return 1; values = ldap_get_values(ld, entry, LDAP_HOME_PARAM); if (values && values[0]) { homeparam = malloc(strlen(values[0]) + strlen("../../") + 1); strcpy(homeparam,values[0]); strcat(homeparam,"../../"); } ldap_msgfree(res); ldap_unbind(ld); return 0; }
/** * The public method auth authenticats the user with username and password * Parameters: * std::string *username: a reverence to the username * std::string *pw: a reverence to the password * Return: * bool: true if auth successfull */ bool LDAPConnection::auth(std::string *username, std::string *pw){ int rc = 0; LDAPMessage *result, *entry; std::string filter = "(uid="; filter.append(*username); filter.append(")"); //searches for user rc = ldap_search_s(this->ld, SEARCHBASE, SCOPE, filter.c_str(), this->attribs, 0, &result); if(rc != LDAP_SUCCESS){ std::cout << ldap_err2string(rc) << std::endl; ldap_msgfree(result); return false; } //counts results if(ldap_count_entries(this->ld, result) != 1){ ldap_msgfree(result); return false; } //gets user dn entry = ldap_first_entry(this->ld, result); std::string dn = ldap_get_dn(this->ld,entry); ldap_msgfree(result); //initializes a new ldap connection LDAP *ldp; ldap_initialize(&ldp, LDAP_HOST); if(ldp == NULL){ return false; } //tries to bind the user rc = ldap_simple_bind_s(ldp, dn.c_str(), pw->c_str()); if(rc != LDAP_SUCCESS){ ldap_unbind(ldp); return false; } //closes the new ldap connection ldap_unbind(ldp); return true; }
/* * ldap_bind_s - bind to the ldap server. The dn and password * of the entry to which to bind are supplied, along with the authentication * method to use. This routine just calls whichever bind routine is * appropriate and returns the result of the bind (e.g. LDAP_SUCCESS or * some other error indication). Note, the kerberos support assumes the * user already has a valid tgt for now. * * Examples: * ldap_bind_s( ld, "cn=manager, o=university of michigan, c=us", * "secret", LDAP_AUTH_SIMPLE ) * ldap_bind_s( ld, "cn=manager, o=university of michigan, c=us", * NULL, LDAP_AUTH_KRBV4 ) */ int LDAP_CALL ldap_bind_s( LDAP *ld, const char *dn, const char *passwd, int authmethod ) { int err; LDAPDebug( LDAP_DEBUG_TRACE, "ldap_bind_s\n", 0, 0, 0 ); switch ( authmethod ) { case LDAP_AUTH_SIMPLE: return( ldap_simple_bind_s( ld, dn, passwd ) ); default: err = LDAP_AUTH_UNKNOWN; LDAP_SET_LDERRNO( ld, err, NULL, NULL ); return( err ); } }
LDAP * ldap_connect() { LDAP *conn = NULL; int err; char *password = NULL; struct passwd *pwd; char *userdn = NULL; if ((pwd = getpwuid(getuid())) == NULL) { (void) fprintf(stderr, "ldap_connect: you don't seem to exist\n"); goto err; } if ((conn = ldap_init(SERVER, PORT)) == NULL) { (void) fprintf(stderr, "ldap_connect: cannot connect to LDAP server: %s:%d: %s\n", SERVER, PORT, strerror(errno)); goto err; } (void) asprintf(&userdn, "uid=%s,%s", pwd->pw_name, BASE_DN); (void) printf("User DN: %s\n", userdn); if ((password = ts_getpass("LDAP Password: "******"ldap_connect: cannot bind as %s: %s\n", userdn, ldap_err2string(err)); goto err; } bzero(password, strlen(password)); return conn; err: if (password) bzero(password, strlen(password)); free(userdn); return NULL; }
bool LdapSearch::init() { if( d->ldap ) return true; if( !(d->ldap = ldap_init( "ldap.sk.ee", 389 )) ) { setLastError( tr("Failed to init ldap"), -1 ); return false; } int version = LDAP_VERSION3; ldap_set_option( d->ldap, LDAP_OPT_PROTOCOL_VERSION, &version ); int err = ldap_simple_bind_s( d->ldap, 0, 0 ); if( err ) setLastError( tr("Failed to init ldap"), err ); return !err; }
static int lua_apr_ldap_bind(lua_State *L) { lua_apr_ldap_object *object; const char *who, *passwd; int status, version; object = check_ldap_connection(L, 1); who = luaL_optstring(L, 2, NULL); passwd = luaL_optstring(L, 3, NULL); /* Default to LDAP v3 */ version = LDAP_VERSION3; status = ldap_set_option(object->ldap, LDAP_OPT_PROTOCOL_VERSION, &version); if (status != LDAP_SUCCESS) return push_ldap_status(L, status); status = ldap_simple_bind_s(object->ldap, (char*)who, (char*)passwd); return push_ldap_status(L, status); }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string LDAP_UNX::getDistinguishedName( const std::string userID, std::string *dname ) { *dname = ""; LDAP *ldap = NULL; // INITIALISE AND CONNECT TO LDAP SERVER std::string e = initialize( &ldap ); if ( ! e.empty() ) {return( e ); } std::string base = ou + "," + dc; std::string bparam = std::string("CN=LDAPbind,") + base; const int ibind = ldap_simple_bind_s( ldap, bparam.c_str(), ldap_pw.c_str() ); if ( ibind != LDAP_SUCCESS ) {sprintf( ebuf, "ldap_simple_bind_s=%d", ibind ); return( std::string(ebuf) ); } /* SEARCH FOR ENTRY WITH sAMAccountName AS GIVEN BY USER AND GET distinguishedName IF IT EXISTS (IF FOUND, THEN USERNAME EXISTS) */ LDAPMessage *res = ( LDAPMessage * )NULL; std::string filter = "(sAMAccountName=" + userID + ")"; const int isearch = ldap_search_s( ldap, base.c_str(), LDAP_SCOPE_ONELEVEL, filter.c_str(), ( char ** )NULL, 0, &res ); if ( isearch != LDAP_SUCCESS ) {sprintf( ebuf, "ldap_search_s=%d", isearch ); return( std::string(ebuf) ); } const int nentries = ldap_count_entries( ldap, res ); if ( nentries <= 0 ) { // FAILED TO FIND distinguishedName from sAMAccountName ldap_msgfree( res ); ldap_unbind_s( ldap ); return( "Username not found in LDAP-OU" ); } // EXTRACT distinguishedNAme char *dn = ldap_get_dn( ldap, ldap_first_entry( ldap, res ) ); *dname = std::string( dn ); ldap_memfree( dn ); // TIDY UP ldap_msgfree( res ); ldap_unbind_s( ldap ); // DROP ASSOCIATION return( "" ); }
/** * The LDAPConnection handels the authentication of the user */ LDAPConnection::LDAPConnection(){ int rc = 0; attribs[0] = strdup("uid"); attribs[1] = NULL; //initialize the ldap connection ldap_initialize(&this->ld, LDAP_HOST); if(this->ld == NULL){ std::cerr << "ldap_initialization failed" << std::endl; exit(7); } //binds the ldap connection rc = ldap_simple_bind_s(this->ld, BIND_USER, BIND_PW); if(rc != LDAP_SUCCESS){ std::cerr << "could not login to LDAP-server." << std::endl; exit(8); } }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string LDAP_UNX::authenticate( const std::string userID, const std::string password ) { std::string dist_name; std::string e = getDistinguishedName( userID, &dist_name ); if ( ! e.empty() ) {return( e ); } LDAP *ldap = NULL; // INITIALISE AND CONNECT TO LDAP SERVER e = initialize( &ldap ); if ( ! e.empty() ) {return( e ); } // ATTEMPT TO BIND distinguishedName WITH PASSWORD GIVEN const int ibind = ldap_simple_bind_s( ldap, dist_name.c_str(), password.c_str() ); ldap_unbind_s( ldap ); return( ( LDAP_SUCCESS == ibind ) ? "" : "Username/password mis-match" ); }
static int ldapconnect(LDAP **ldapconn, mod_vhost_ldap_config_t *conf) { int ldapversion = LDAP_VERSION3; int ret; if(*ldapconn == NULL){ if((ret = ldap_initialize(ldapconn, conf->url)) > 0){ *ldapconn = NULL; return ret; } if((ret = ldap_set_option(*ldapconn, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) > 0){ *ldapconn = NULL; return ret; } if ((ret = ldap_simple_bind_s(*ldapconn, conf->binddn, conf->bindpw)) != LDAP_SUCCESS){ ldap_unbind(*ldapconn); *ldapconn = NULL; return ret; } } return 0; }
/** connect to ldap and bind as data->binddn */ static int _ldapfull_connect_bind(moddata_t data) { if(data->ld != NULL && data->binded ) { return 0; } if( _ldapfull_connect(data) ) { return 1; } if(ldap_simple_bind_s(data->ld, data->binddn, data->bindpw)) { log_write(data->ar->c2s->log, LOG_ERR, "ldap: bind as '%s' failed: %s", data->binddn, ldap_err2string(_ldapfull_get_lderrno(data->ld))); _ldapfull_unbind(data); return 1; } log_debug(ZONE, "binded to ldap server"); data->binded = 1; return 0; }
static int user_bind(char *connstr, char *dn, const char *password) { LDAP *ld; int opt, rc; if (ldap_initialize(&ld, connstr) != LDAP_SUCCESS) { _log(1, "Cannot ldap_initialize-2"); return (FALSE); } opt = LDAP_VERSION3; ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &opt); if ((rc = ldap_simple_bind_s(ld, dn, password)) != LDAP_SUCCESS) { _log(1, "Cannot bind to LDAP as %s: %s", dn, ldap_err2string(rc)); return (FALSE); } ldap_unbind(ld); return (TRUE); }
static void *bind_thread(char *id) { char dn[BUFSIZ], name[40]; int rc, opcount; void *voidrc = (void *)0; printf("Starting bind_thread %s.\n", id); opcount = 0; tsd_setup(); for (;;) { sprintf(name, "%d", get_random_id()); sprintf(dn, "cn=%s, " BASE, name); printf("Thread %s: Binding as entry (%s)\n", id, dn); if ((rc = ldap_simple_bind_s(ld, dn, name)) != LDAP_SUCCESS) { ldap_perror(ld, "ldap_simple_bind_s"); if (rc == LDAP_SERVER_DOWN) { perror("ldap_simple_bind_s"); voidrc = (void *)1; goto bind_cleanup_and_return; } } else { printf("Thread %s: bound as entry (%s)\n", id, dn); } ++opcount; if (maxops != 0 && opcount >= maxops) { break; } } bind_cleanup_and_return: printf("Thread %s: attempted %d bind operations\n", id, opcount); set_ld_error(0, NULL, NULL, NULL); /* disposes of memory */ tsd_cleanup(); free(id); return voidrc; }
/* optionally perform a bind */ static int lldb_bind(struct ldb_module *module, const char *options[]) { const char *bind_mechanism; struct lldb_private *lldb; struct ldb_context *ldb = ldb_module_get_ctx(module); int ret; bind_mechanism = ldb_options_find(ldb, options, "bindMech"); if (bind_mechanism == NULL) { /* no bind wanted */ return LDB_SUCCESS; } lldb = talloc_get_type(ldb_module_get_private(module), struct lldb_private); if (strcmp(bind_mechanism, "simple") == 0) { const char *bind_id, *bind_secret; bind_id = ldb_options_find(ldb, options, "bindID"); bind_secret = ldb_options_find(ldb, options, "bindSecret"); if (bind_id == NULL || bind_secret == NULL) { ldb_asprintf_errstring(ldb, "simple bind requires bindID and bindSecret"); return LDB_ERR_OPERATIONS_ERROR; } ret = ldap_simple_bind_s(lldb->ldap, bind_id, bind_secret); if (ret != LDAP_SUCCESS) { ldb_asprintf_errstring(ldb, "bind failed: %s", ldap_err2string(ret)); return ret; } return LDB_SUCCESS; } ldb_asprintf_errstring(ldb, "bind failed: unknown mechanism %s", bind_mechanism); return LDB_ERR_INAPPROPRIATE_AUTHENTICATION; }
/******************************************************************************* 函数名称 : 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; }
static int ldaplookup_bind_s(LDAP *ld) { int result; /* anonymous bind - data must be retrieved by anybody */ #ifdef HAVE_LDAP_SASL_BIND_S { static struct berval cred = { 0, (char*)"" }; result = ldap_sasl_bind_s( ld, NULL/*dn*/, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL); } #else result = ldap_simple_bind_s(ld, NULL/*binddn*/, NULL/*bindpw*/); #endif #ifdef TRACE_BY_LDAP fprintf(stderr, "TRACE_BY_LDAP ldaplookup_bind_s:" " ldap_XXX_bind_s return 0x%x(%s)\n" , result, ldap_err2string(result)); #endif return(result); }
/** LDAP* open_ldap_connection(char* fn) 設定ファイルを読み込み後,LDAPサーバに接続する @param fn 設定の格納されたファイル名.fn, /etc/openldap/ldap.conf, /etc/ldap.conf を順に読んで大域変数 JBXLdapHost, JBXLdapDnBind に情報を格納する. @return LDAPサーバへのセッションハンドラ.接続に失敗した場合は NULL */ LDAP* open_ldap_connection(char* fn) { if (JBXLdapHost==NULL||JBXLdapDnBind==NULL||fn!=NULL) read_ldap_config_file(fn); if (JBXLdapHost==NULL||JBXLdapDnBind==NULL) return NULL; if (JBXLdapDnBind->dnbind.buf==NULL) return NULL; if (JBXLdapDnBind->passwd.buf==NULL) return NULL; if (JBXLdapDnBind->passwd.buf[0]=='\0') return NULL; if (JBXLdapHost->hostname.buf==NULL) return NULL; if (JBXLdapHost->port<=0) return NULL; int ret; LDAP* ld = NULL; if (JBXLdapHost->useSSL!=TRUE || JBXLdapHost->port==389) { DEBUG_MODE print_message("INFO LDAP NORMAL Mode\n"); ld = ldap_init((char*)JBXLdapHost->hostname.buf, JBXLdapHost->port); if (ld==NULL) { DEBUG_MODE print_message("ERR LDAP Init error.\n"); return NULL; } if (JBXLdapHost->useSSL==TRUE) { // STARTTLS (動作未確認) DEBUG_MODE print_message("INFO LDAP STARTTLS Mode\n"); ret = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &JBXLdapHost->reqCert); if (ret!=LDAP_SUCCESS) { DEBUG_MODE print_message("ERR LDAP STARTTLS Require Cert = %s\n", ldap_err2string(ret)); ldap_unbind_s(ld); return NULL; } int ldap_vers = LDAP_VERSION3; ret = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldap_vers); if (ret!=LDAP_SUCCESS) { DEBUG_MODE print_message("ERR LDAP STARTTLS Version = %s\n", ldap_err2string(ret)); ldap_unbind_s(ld); return NULL; } // ret = ldap_start_tls_s(ld, NULL, NULL); if (ret!=LDAP_SUCCESS) { DEBUG_MODE print_message("ERR LDAP STARTTLS Start = %s\n", ldap_err2string(ret)); ldap_unbind_s(ld); return NULL; } } } // else { // LDAP over SSL DEBUG_MODE print_message("INFO LDAP Over SSL Mode\n"); Buffer url = make_Buffer_bystr("ldaps://"); cat_Buffer(&JBXLdapHost->hostname, &url); cat_s2Buffer(":", &url); cat_s2Buffer(itostr(JBXLdapHost->port), &url); DEBUG_MODE print_message("INFO LDAP SSL URL = %s\n", (char*)url.buf); // ret = ldap_initialize(&ld, (char*)url.buf); free_Buffer(&url); if (ret!=LDAP_SUCCESS) { DEBUG_MODE print_message("ERR LDAP SSL Init = %s\n", ldap_err2string(ret)); return NULL; } // ret = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &JBXLdapHost->reqCert); if (ret!=LDAP_SUCCESS) { DEBUG_MODE print_message("ERR LDAP SSL Require Cert = %s\n", ldap_err2string(ret)); ldap_unbind_s(ld); return NULL; } } ret = ldap_simple_bind_s(ld, (char*)JBXLdapDnBind->dnbind.buf, (char*)JBXLdapDnBind->passwd.buf); if (ret!=LDAP_SUCCESS) { DEBUG_MODE print_message("ERR LDAP Bind = %s\n", ldap_err2string(ret)); ldap_unbind_s(ld); return NULL; } return ld; }
int main( int argc, char **argv ) { LDAP *ld; LDAPMessage *result, *e; char *attrfail, *matched = NULL, *errmsg = NULL; char **vals, **referrals; int rc, parse_rc, version; unsigned long sortrc; LDAPControl *sortctrl = NULL; LDAPControl *requestctrls[ 2 ]; LDAPControl **resultctrls = NULL; LDAPsortkey **sortkeylist; /* Arrange for all connections to use LDAPv3 */ version = LDAP_VERSION3; if ( ldap_set_option( NULL, LDAP_OPT_PROTOCOL_VERSION, &version ) != 0 ) { fprintf( stderr, "ldap_set_option protocol version to %d failed\n", version ); return( 1 ); } /* Get a handle to an LDAP connection */ if ( (ld = ldap_init( MY_HOST, MY_PORT ) ) == NULL ) { perror( "ldap_init" ); return( 1 ); } /* Authenticate as Directory Manager */ if ( ldap_simple_bind_s( ld, MGR_DN, MGR_PW ) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_simple_bind_s" ); ldap_unbind( ld ); return( 1 ); } /* * Create a sort key list that specifies the sort order of the results. * Sort the results by last name first, then by first name. */ ldap_create_sort_keylist( &sortkeylist, "description -givenname" ); /* Create the sort control. */ rc = ldap_create_sort_control( ld, sortkeylist, 1, &sortctrl ); if ( rc != LDAP_SUCCESS ) { fprintf( stderr, "ldap_create_sort_control: %s\n", ldap_err2string( rc ) ); ldap_unbind( ld ); return( 1 ); } requestctrls[ 0 ] = sortctrl; requestctrls[ 1 ] = NULL; /* Search for all entries in Sunnyvale */ rc = ldap_search_ext_s( ld, PEOPLE_BASE, LDAP_SCOPE_SUBTREE, "(objectclass=person)", NULL, 0, requestctrls, NULL, NULL, 0, &result ); if ( rc != LDAP_SUCCESS ) { fprintf( stderr, "ldap_search_ext_s: %s\n", ldap_err2string( rc ) ); ldap_unbind( ld ); return( 1 ); } parse_rc = ldap_parse_result( ld, result, &rc, &matched, &errmsg, &referrals, &resultctrls, 0 ); if ( parse_rc != LDAP_SUCCESS ) { fprintf( stderr, "ldap_parse_result: %s\n", ldap_err2string( parse_rc ) ); ldap_unbind( ld ); return( 1 ); } if ( rc != LDAP_SUCCESS ) { fprintf( stderr, "ldap_search_ext_s: %s\n", ldap_err2string( rc ) ); if ( errmsg != NULL && *errmsg != '\0' ) { fprintf( stderr, "%s\n", errmsg ); } ldap_unbind( ld ); return( 1 ); } parse_rc = ldap_parse_sort_control( ld, resultctrls, &sortrc, &attrfail ); if ( parse_rc != LDAP_SUCCESS ) { fprintf( stderr, "ldap_parse_sort_control: %s\n", ldap_err2string( parse_rc ) ); ldap_unbind( ld ); return( 1 ); } if ( sortrc != LDAP_SUCCESS ) { fprintf( stderr, "Sort error: %s\n", ldap_err2string( sortrc )); if ( attrfail != NULL && *attrfail != '\0' ) { fprintf( stderr, "Bad attribute: %s\n", attrfail); } ldap_unbind( ld ); return( 1 ); } /* for each entry print out name + all attrs and values */ for ( e = ldap_first_entry( ld, result ); e != NULL; e = ldap_next_entry( ld, e ) ) { if ((vals = ldap_get_values( ld, e, "sn")) != NULL ) { if ( vals[0] != NULL ) { printf( "%s", vals[0] ); } ldap_value_free( vals ); } if ((vals = ldap_get_values( ld, e, "givenname")) != NULL ) { if ( vals[0] != NULL ) { printf( "\t%s", vals[0] ); } ldap_value_free( vals ); } putchar( '\n' ); } ldap_msgfree( result ); ldap_free_sort_keylist( sortkeylist ); ldap_control_free( sortctrl ); ldap_controls_free( resultctrls ); ldap_unbind( ld ); return( 0 ); }
/* * This function will look in ldap id the token correspond to the * requested user. It will returns 0 for failure and 1 for success. * * For the moment ldaps is not supported. ldap serve can be on a * remote host. * * You need the following parameters in you pam config: * ldapserver= OR ldap_uri= * ldapdn= * user_attr= * yubi_attr= * */ static int authorize_user_token_ldap (struct cfg *cfg, const char *user, const char *token_id) { DBG(("called")); int retval = 0; int protocol; #ifdef HAVE_LIBLDAP LDAP *ld = NULL; LDAPMessage *result = NULL, *e; BerElement *ber; char *a; char *attrs[2] = {NULL, NULL}; struct berval **vals; int i, rc; char *find = NULL, *sr = NULL; if (cfg->user_attr == NULL) { DBG (("Trying to look up user to YubiKey mapping in LDAP, but user_attr not set!")); return 0; } if (cfg->yubi_attr == NULL) { DBG (("Trying to look up user to YubiKey mapping in LDAP, but yubi_attr not set!")); return 0; } if (cfg->ldapdn == NULL) { DBG (("Trying to look up user to YubiKey mapping in LDAP, but ldapdn not set!")); return 0; } /* Get a handle to an LDAP connection. */ if (cfg->ldap_uri) { rc = ldap_initialize (&ld, cfg->ldap_uri); if (rc != LDAP_SUCCESS) { DBG (("ldap_init: %s", ldap_err2string (rc))); retval = 0; goto done; } } else { if ((ld = ldap_init (cfg->ldapserver, PORT_NUMBER)) == NULL) { DBG (("ldap_init")); retval = 0; goto done; } } /* LDAPv2 is historical -- RFC3494. */ protocol = LDAP_VERSION3; ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &protocol); /* Bind anonymously to the LDAP server. */ rc = ldap_simple_bind_s (ld, NULL, NULL); if (rc != LDAP_SUCCESS) { DBG (("ldap_simple_bind_s: %s", ldap_err2string (rc))); retval = 0; goto done; } /* Allocation of memory for search strings depending on input size */ find = malloc((strlen(cfg->user_attr)+strlen(cfg->ldapdn)+strlen(user)+3)*sizeof(char)); sprintf (find, "%s=%s,%s", cfg->user_attr, user, cfg->ldapdn); attrs[0] = (char *) cfg->yubi_attr; DBG(("LDAP : look up object '%s', ask for attribute '%s'", find, cfg->yubi_attr)); /* Search for the entry. */ if ((rc = ldap_search_ext_s (ld, find, LDAP_SCOPE_BASE, NULL, attrs, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result)) != LDAP_SUCCESS) { DBG (("ldap_search_ext_s: %s", ldap_err2string (rc))); retval = 0; goto done; } e = ldap_first_entry (ld, result); if (e == NULL) { DBG (("No result from LDAP search")); } else { /* Iterate through each returned attribute. */ for (a = ldap_first_attribute (ld, e, &ber); a != NULL; a = ldap_next_attribute (ld, e, ber)) { if ((vals = ldap_get_values_len (ld, e, a)) != NULL) { /* Compare each value for the attribute against the token id. */ for (i = 0; vals[i] != NULL; i++) { if (!strncmp (token_id, vals[i]->bv_val, strlen (token_id))) { DBG (("Token Found :: %s", vals[i]->bv_val)); retval = 1; } else { DBG (("No match : (%s) %s != %s", a, vals[i]->bv_val, token_id)); } } ldap_value_free_len (vals); } ldap_memfree (a); } if (ber != NULL) ber_free (ber, 0); } done: if (result != NULL) ldap_msgfree (result); if (ld != NULL) ldap_unbind (ld); /* free memory allocated for search strings */ if (find != NULL) free(find); if (sr != NULL) free(sr); #else DBG (("Trying to use LDAP, but this function is not compiled in pam_yubico!!")); DBG (("Install libldap-dev and then recompile pam_yubico.")); #endif return retval; }
abook_fielddata * abook_ldap_fetch(char *alias, int *count) { int i, rc, ldapcount, mappedfieldcount; char *ptr; char prefix[1024]; char filter[1024]; abook_fielddata *fdata, *fptr; char *searchattr; char *searchkey; LDAP *ld; LDAPMessage *results, *entry; char **values; if (config_ldap() < 0) { syslog(LOG_ERR, "abook_ldap_fetch: failed to configure LDAP"); return NULL; } /* * Decide how to search for the user. */ snprintf(prefix, sizeof(prefix), "[%s:", config.uniqueattr); ptr = strstr(alias, prefix); if (ptr != NULL) { *ptr = '\0'; ptr += 1 /*[*/ + strlen(config.uniqueattr) + 1 /*:*/; searchkey = ptr; ptr += strlen(ptr) - 1 /*]*/; *ptr = '\0'; searchattr = config.uniqueattr; } else { searchkey = alias; searchattr = config.fullnameattr; } snprintf(filter, sizeof(filter), "(&%s(%s=%s))", config.defaultfilter, searchattr, searchkey); ld = ldap_init(config.ldaphost, config.ldapport); if (ld == NULL) { syslog(LOG_ERR, "abook_ldap_fetch: LDAP init failed: %s", strerror(errno)); return NULL; } rc = ldap_simple_bind_s(ld, NULL, NULL); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_fetch: simple bind failed: %s", ldap_err2string(rc)); return NULL; } rc = ldap_search_s(ld, config.searchbase, config.scope, filter, NULL/*get all attrs*/, 0/*attrs-only*/, &results); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_fetch: LDAP search failed: %s", ldap_err2string(rc)); ldap_unbind(ld); return NULL; } ldapcount = ldap_count_entries(ld, results); if (ldapcount == 0) { /* no matches on primary search, try secondary search if configured */ if (secondaryconfig.ldaphost) { /* close the connection to the primary server */ ldap_unbind(ld); snprintf(prefix, sizeof(prefix), "[%s:", secondaryconfig.uniqueattr); ptr = strstr(alias, prefix); if (ptr != NULL) { *ptr = '\0'; ptr += 1 /*[*/ + strlen(secondaryconfig.uniqueattr) + 1 /*:*/; searchkey = ptr; ptr += strlen(ptr) - 1 /*]*/; *ptr = '\0'; searchattr = secondaryconfig.uniqueattr; } else { searchkey = alias; searchattr = secondaryconfig.fullnameattr; } snprintf(filter, sizeof(filter), "(&%s(%s=%s))", secondaryconfig.defaultfilter, searchattr, searchkey); ld=ldap_init(secondaryconfig.ldaphost, secondaryconfig.ldapport); if (ld == NULL){ syslog(LOG_ERR, "abook_ldap_fetch: LDAP secondary init failed: %s", strerror(errno)); return NULL; } rc = ldap_simple_bind_s(ld, NULL, NULL); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_fetch: simple secondary bind failed: %s", ldap_err2string(rc)); return NULL; } rc = ldap_search_s(ld, secondaryconfig.searchbase, secondaryconfig.scope, filter, NULL/*get all attrs*/, 0/*attrs-only*/, &results); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_fetch: LDAP secondary search failed: %s", ldap_err2string(rc)); ldap_unbind(ld); return NULL; } ldapcount = ldap_count_entries(ld, results); if (ldapcount != 1) { syslog(LOG_ERR, "abook_ldap_fetch: unexpected count of secondary search" " hits: %d", ldapcount); (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return NULL; } entry = ldap_first_entry(ld, results); if (entry == NULL) { syslog(LOG_ERR, "abook_ldap_fetch: ldap_first_entry failed"); (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return NULL; } /* This memory is freed by abook_fetchdone() which is called by * show_address() after it's finished sending the field/data pairs * back to the IMSP client */ mappedfieldcount = 0; for (i = 0; secondaryconfig.map[i].field != NULL; i++) { if (secondaryconfig.map[i].attr != NULL) mappedfieldcount++; } fdata = (abook_fielddata *) malloc(sizeof (abook_fielddata) * mappedfieldcount); if (fdata == NULL) { syslog(LOG_ERR, "abook_ldap_fetch: Out of memory"); (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return NULL; } *count = 0; fptr = fdata; for (i = 0; secondaryconfig.map[i].field != NULL; i++) { if ((secondaryconfig.map[i].attr != NULL) && (strcmp(secondaryconfig.map[i].attr, secondaryconfig.fullnameattr) != 0)) { values = ldap_get_values(ld, entry, secondaryconfig.map[i].attr); if (values != NULL && values[0] != NULL) { fptr->field = strdup(secondaryconfig.map[i].field); if (secondaryconfig.map[i].append != NULL) { int fptrdatalen = strlen(values[0])+strlen(secondaryconfig.map[i].append)+1; fptr->data=malloc(fptrdatalen); if(!fptr->data) fatal("out of memory", EC_TEMPFAIL); strlcpy(fptr->data, values[0], fptrdatalen); strlcat(fptr->data, secondaryconfig.map[i].append, fptrdatalen); } else { fptr->data = strdup(values[0]); if(!fptr->data) fatal("out of memory", EC_TEMPFAIL); } (*count)++; fptr++; } if (values != NULL) ldap_value_free(values); } } (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return (fdata); } } if (ldapcount != 1) { syslog(LOG_ERR, "abook_ldap_fetch: unexpected count of search" " hits: %d", ldapcount); (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return NULL; } entry = ldap_first_entry(ld, results); if (entry == NULL) { syslog(LOG_ERR, "abook_ldap_fetch: ldap_first_entry failed"); (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return NULL; } /* This memory is freed by abook_fetchdone() which is called by * show_address() after it's finished sending the field/data pairs * back to the IMSP client */ mappedfieldcount = 0; for (i = 0; config.map[i].field != NULL; i++) { if (config.map[i].attr != NULL) mappedfieldcount++; } fdata = (abook_fielddata *) malloc(sizeof (abook_fielddata) * mappedfieldcount); if (fdata == NULL) { syslog(LOG_ERR, "abook_ldap_fetch: Out of memory"); (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return NULL; } *count = 0; fptr = fdata; for (i = 0; config.map[i].field != NULL; i++) { if ((config.map[i].attr != NULL) && (strcmp(config.map[i].attr, config.fullnameattr) != 0)) { values = ldap_get_values(ld, entry, config.map[i].attr); if (values != NULL && values[0] != NULL) { fptr->field = strdup(config.map[i].field); if (config.map[i].append != NULL) { printf("appending %s to field: %s value: %s\n", config.map[i].append, config.map[i].field,values[0]); fptr->data=malloc(strlen(values[0])+strlen(config.map[i].append)+1); fptr->data=strcat(fptr->data, values[0]); fptr->data=strcat(fptr->data, config.map[i].append); } else { fptr->data = strdup(values[0]); } (*count)++; fptr++; } if (values != NULL) ldap_value_free(values); } } (void) ldap_msgfree(results); /* ignore message type return value */ ldap_unbind(ld); return (fdata); }
int abook_ldap_searchstart(abook_ldap_state **ldap_state, abook_fielddata *flist, int fcount) { abook_ldap_state *mystate; int msgid, rc; int sizelimit; char *msg; char *attrs[20]; LDAP *ld; LDAPMessage *result; char *filter, *secondaryfilter; int searching_secondary = 0; if (config_ldap() < 0) { syslog(LOG_ERR, "abook_ldap_searchstart: failed to configure LDAP"); return -1; } if (imsp_to_ldap_filter(flist, fcount, &filter, config) < 0) { syslog(LOG_ERR, "abook_ldap_searchstart: failed to convert filter"); return -1; } ld = ldap_init(config.ldaphost, config.ldapport); if (ld == NULL) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP init failed: %s", strerror(errno)); return -1; } rc = ldap_simple_bind_s(ld, NULL, NULL); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_searchstart: simple bind failed: %s", ldap_err2string(rc)); return -1; } /* For testing the error handlers... sizelimit = 4; ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &sizelimit); */ attrs[0] = config.fullnameattr; attrs[1] = config.uniqueattr; attrs[2] = NULL; msgid = ldap_search(ld, config.searchbase, config.scope, filter, attrs, 0/*attrs-only*/); if (msgid == -1) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP search failed"); ldap_unbind(ld); return -1; } rc = ldap_result(ld, msgid, 0, NULL, &result); switch (rc) { case LDAP_RES_SEARCH_ENTRY: /* Do nothing here. The abook_search function will pull out this * entry and send it back for display to the user. * The result is freed later. */ break; case LDAP_RES_SEARCH_RESULT: rc = ldap_result2error(ld, result, 1 /* free result */); if (rc == LDAP_SUCCESS) { /* * Search returned successfully, but with no matching entries. * * Try to do the secondary search, if configured to do so. * fails, then set the prevresult to NULL. */ if (secondaryconfig.ldaphost) { searching_secondary = 1; /* close the connection to the primary ldap server */ ldap_unbind(ld); if (imsp_to_ldap_filter(flist, fcount, &secondaryfilter, secondaryconfig) < 0) { syslog(LOG_ERR, "abook_ldap_searchstart: failed to convert filter"); return -1; } /* open connection to the secondary server */ ld = ldap_init(secondaryconfig.ldaphost, secondaryconfig.ldapport); if (ld == NULL) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP init failed: %s", strerror(errno)); return -1; } rc = ldap_simple_bind_s(ld, NULL, NULL); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_searchstart: simple bind failed: %s", ldap_err2string(rc)); return -1; } attrs[0] = secondaryconfig.fullnameattr; attrs[1] = secondaryconfig.uniqueattr; attrs[2] = NULL; msgid = ldap_search(ld, secondaryconfig.searchbase, secondaryconfig.scope, secondaryfilter, attrs, 0 /*attrs-only*/); if (msgid == -1) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP search failed"); ldap_unbind(ld); return -1; } rc = ldap_result(ld, msgid, 0, NULL, &result); switch (rc) { case LDAP_RES_SEARCH_ENTRY: /* Do nothing here. The abook_search function will pull out this * entry and send it back for display to the user. * The result is freed later. */ break; case LDAP_RES_SEARCH_RESULT: /* Still didn't get any data. Send a null "prevresult" to the * abook_search function. */ result = NULL; break; default: syslog(LOG_ERR, "abook_ldap_searchstart: ldap_result failed: %s (%d)", ldap_err2string(rc), rc); (void) ldap_msgfree(result); /* ignore message type return value */ ldap_unbind(ld); return -1; } } /* if (secondaryconfig.ldaphost) */ } else { syslog(LOG_ERR,"abook_ldap_searchstart: search returned error: %s", ldap_err2string(rc)); ldap_unbind(ld); return -1; } break; default: syslog(LOG_ERR, "abook_ldap_searchstart: ldap_result failed: A1 SEARCHADDRESS %s", ldap_err2string(rc)); (void) ldap_msgfree(result); /* ignore message type return value */ ldap_unbind(ld); return -1; } mystate = (abook_ldap_state *) malloc (sizeof (abook_ldap_state)); *ldap_state = mystate; if (mystate == NULL) { syslog(LOG_ERR, "abook_ldap_searchstart: Out of memory"); (void) ldap_msgfree(result); /* ignore message type return value */ ldap_unbind(ld); return -1; } mystate->ld = ld; mystate->msgid = msgid; mystate->prevresult = result; if (searching_secondary == 0) { mystate->ldapconfig = &config; } else { mystate->ldapconfig = &secondaryconfig; } return 0; }
CURLcode Curl_ldap(struct connectdata *conn) { CURLcode status = CURLE_OK; int rc; void *(*ldap_init)(char *, int); int (*ldap_simple_bind_s)(void *, char *, char *); int (*ldap_unbind_s)(void *); int (*ldap_url_parse)(char *, LDAPURLDesc **); void (*ldap_free_urldesc)(void *); int (*ldap_search_s)(void *, char *, int, char *, char **, int, void **); int (*ldap_search_st)(void *, char *, int, char *, char **, int, void *, void **); void *(*ldap_first_entry)(void *, void *); void *(*ldap_next_entry)(void *, void *); char *(*ldap_err2string)(int); char *(*ldap_get_dn)(void *, void *); char *(*ldap_first_attribute)(void *, void *, void **); char *(*ldap_next_attribute)(void *, void *, void *); char **(*ldap_get_values)(void *, void *, char *); void (*ldap_value_free)(char **); void (*ldap_memfree)(void *); void (*ber_free)(void *, int); void *server; LDAPURLDesc *ludp; void *result; void *entryIterator; void *ber; void *attribute; 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; } /* The types are needed because ANSI C distinguishes between * pointer-to-object (data) and pointer-to-function. */ DYNA_GET_FUNCTION(void *(*)(char *, int), ldap_init); DYNA_GET_FUNCTION(int (*)(void *, char *, char *), ldap_simple_bind_s); DYNA_GET_FUNCTION(int (*)(void *), ldap_unbind_s); DYNA_GET_FUNCTION(int (*)(char *, LDAPURLDesc **), ldap_url_parse); DYNA_GET_FUNCTION(void (*)(void *), ldap_free_urldesc); DYNA_GET_FUNCTION(int (*)(void *, char *, int, char *, char **, int, void **), ldap_search_s); DYNA_GET_FUNCTION(int (*)(void *, char *, int, char *, char **, int, void *, void **), ldap_search_st); 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(char *(*)(void *, void *), ldap_get_dn); DYNA_GET_FUNCTION(char *(*)(void *, void *, void **), ldap_first_attribute); DYNA_GET_FUNCTION(char *(*)(void *, void *, void *), ldap_next_attribute); DYNA_GET_FUNCTION(char **(*)(void *, void *, char *), ldap_get_values); DYNA_GET_FUNCTION(void (*)(char **), ldap_value_free); DYNA_GET_FUNCTION(void (*)(void *), ldap_memfree); DYNA_GET_FUNCTION(void (*)(void *, int), ber_free); server = ldap_init(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?conn->user:NULL, conn->bits.user_passwd?conn->passwd:NULL); if (rc != 0) { failf(data, "LDAP: %s", ldap_err2string(rc)); status = CURLE_LDAP_CANNOT_BIND; } else { rc = ldap_url_parse(data->change.url, &ludp); if (rc != 0) { failf(data, "LDAP: %s", ldap_err2string(rc)); status = CURLE_LDAP_INVALID_URL; } else { rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope, ludp->lud_filter, ludp->lud_attrs, 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)) { char *dn = ldap_get_dn(server, entryIterator); char **vals; int i; Curl_client_write(data, CLIENTWRITE_BODY, (char *)"DN: ", 4); Curl_client_write(data, CLIENTWRITE_BODY, dn, 0); Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); for(attribute = ldap_first_attribute(server, entryIterator, &ber); attribute; attribute = ldap_next_attribute(server, entryIterator, ber) ) { vals = ldap_get_values(server, entryIterator, attribute); if (vals != NULL) { for(i = 0; (vals[i] != NULL); i++) { Curl_client_write(data, CLIENTWRITE_BODY, (char*)"\t", 1); Curl_client_write(data, CLIENTWRITE_BODY, attribute, 0); Curl_client_write(data, CLIENTWRITE_BODY, (char *)": ", 2); Curl_client_write(data, CLIENTWRITE_BODY, vals[i], 0); Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 0); } } /* Free memory used to store values */ ldap_value_free(vals); } Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); ldap_memfree(attribute); ldap_memfree(dn); if (ber) ber_free(ber, 0); } } ldap_free_urldesc(ludp); } ldap_unbind_s(server); } } DynaClose(); /* no data to transfer */ Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return status; }
int main( int argc, char **argv ) { LDAP *ld; LDAPMessage *result, *e; BerElement *ber; char *host, *a, *dn; char **vals; int i; int rc; int finished; int msgid; int num_entries = 0; struct timeval zerotime; if ( argc > 1 ) { host = argv[1]; } else { host = MY_HOST; } zerotime.tv_sec = zerotime.tv_usec = 0L; if ( prldap_install_routines( NULL, 1 /* shared */ ) != LDAP_SUCCESS ) { ldap_perror( NULL, "prldap_install_routines" ); return( 1 ); } /* get a handle to an LDAP connection */ if ( (ld = ldap_init( host, MY_PORT )) == NULL ) { perror( host ); return( 1 ); } /* authenticate to the directory as nobody */ if ( ldap_simple_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_simple_bind_s" ); return( 1 ); } /* search for all entries with surname of Jensen */ if (( msgid = ldap_search( ld, MY_SEARCHBASE, LDAP_SCOPE_SUBTREE, MY_FILTER, NULL, 0 )) < 0 ) { ldap_perror( ld, "ldap_search" ); return( 1 ); } /* Loop, polling for results until finished */ finished = 0; while ( !finished ) { /* * Poll for results. We call ldap_result with the "all" argument * set to LDAP_MSG_ONE. This causes ldap_result() to return exactly one * entry if at least one entry is available. This allows us to * display the entries as they are received. */ result = NULL; rc = ldap_result( ld, msgid, LDAP_MSG_ONE, &zerotime, &result ); switch ( rc ) { case -1: /* some error occurred */ ldap_perror( ld, "ldap_result" ); return( 1 ); case 0: /* Timeout was exceeded. No entries are ready for retrieval. */ if ( result != NULL ) { ldap_msgfree( result ); } break; default: /* * Either an entry is ready for retrieval, or all entries have * been retrieved. */ if (( e = ldap_first_entry( ld, result )) == NULL ) { /* All done */ finished = 1; if ( result != NULL ) { ldap_msgfree( result ); } continue; } /* for each entry print out name + all attrs and values */ num_entries++; if (( dn = ldap_get_dn( ld, e )) != NULL ) { printf( "dn: %s\n", dn ); ldap_memfree( dn ); } for ( a = ldap_first_attribute( ld, e, &ber ); a != NULL; a = ldap_next_attribute( ld, e, ber ) ) { if (( vals = ldap_get_values( ld, e, a )) != NULL ) { for ( i = 0; vals[ i ] != NULL; i++ ) { printf( "%s: %s\n", a, vals[ i ] ); } ldap_value_free( vals ); } ldap_memfree( a ); } if ( ber != NULL ) { ber_free( ber, 0 ); } printf( "\n" ); ldap_msgfree( result ); } /* Do other work here while you are waiting... */ do_other_work(); } /* All done. Print a summary. */ printf( "%d entries retrieved. I counted to %ld " "while I was waiting.\n", num_entries, global_counter ); ldap_unbind( ld ); 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; } }
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; }
static CURLcode Curl_ldap(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; int rc = 0; LDAP *server = NULL; LDAPURLDesc *ludp = NULL; LDAPMessage *ldapmsg = NULL; LDAPMessage *entryIterator; int num = 0; struct SessionHandle *data=conn->data; int ldap_proto = LDAP_VERSION3; int ldap_ssl = 0; char *val_b64 = NULL; size_t val_b64_sz = 0; curl_off_t dlsize = 0; #ifdef LDAP_OPT_NETWORK_TIMEOUT struct timeval ldap_timeout = {10,0}; /* 10 sec connection/search timeout */ #endif *done = TRUE; /* unconditionally */ infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d\n", LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION); infof(data, "LDAP local: %s\n", data->change.url); #ifdef HAVE_LDAP_URL_PARSE rc = ldap_url_parse(data->change.url, &ludp); #else rc = _ldap_url_parse(conn, &ludp); #endif if(rc != 0) { failf(data, "LDAP local: %s", ldap_err2string(rc)); result = CURLE_LDAP_INVALID_URL; goto quit; } /* Get the URL scheme ( either ldap or ldaps ) */ if(conn->given->flags & PROTOPT_SSL) ldap_ssl = 1; infof(data, "LDAP local: trying to establish %s connection\n", ldap_ssl ? "encrypted" : "cleartext"); #ifdef LDAP_OPT_NETWORK_TIMEOUT ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout); #endif ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); if(ldap_ssl) { #ifdef HAVE_LDAP_SSL #ifdef CURL_LDAP_WIN /* Win32 LDAP SDK doesn't support insecure mode without CA! */ server = ldap_sslinit(conn->host.name, (int)conn->port, 1); ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON); #else int ldap_option; char* ldap_ca = data->set.str[STRING_SSL_CAFILE]; #if defined(CURL_HAS_NOVELL_LDAPSDK) rc = ldapssl_client_init(NULL, NULL); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } if(data->set.ssl.verifypeer) { /* Novell SDK supports DER or BASE64 files. */ int cert_type = LDAPSSL_CERT_FILETYPE_B64; if((data->set.str[STRING_CERT_TYPE]) && (Curl_raw_equal(data->set.str[STRING_CERT_TYPE], "DER"))) cert_type = LDAPSSL_CERT_FILETYPE_DER; if(!ldap_ca) { failf(data, "LDAP local: ERROR %s CA cert not set!", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM")); result = CURLE_SSL_CERTPROBLEM; goto quit; } infof(data, "LDAP local: using %s CA cert '%s'\n", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), ldap_ca); rc = ldapssl_add_trusted_cert(ldap_ca, cert_type); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting %s CA cert: %s", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } ldap_option = LDAPSSL_VERIFY_SERVER; } else ldap_option = LDAPSSL_VERIFY_NONE; rc = ldapssl_set_verify_mode(ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting cert verify mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } server = ldapssl_init(conn->host.name, (int)conn->port, 1); if(server == NULL) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.name, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } #elif defined(LDAP_OPT_X_TLS) if(data->set.ssl.verifypeer) { /* OpenLDAP SDK supports BASE64 files. */ if((data->set.str[STRING_CERT_TYPE]) && (!Curl_raw_equal(data->set.str[STRING_CERT_TYPE], "PEM"))) { failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type!"); result = CURLE_SSL_CERTPROBLEM; goto quit; } if(!ldap_ca) { failf(data, "LDAP local: ERROR PEM CA cert not set!"); result = CURLE_SSL_CERTPROBLEM; goto quit; } infof(data, "LDAP local: using PEM CA cert: %s\n", ldap_ca); rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting PEM CA cert: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } ldap_option = LDAP_OPT_X_TLS_DEMAND; } else ldap_option = LDAP_OPT_X_TLS_NEVER; rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting cert verify mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } server = ldap_init(conn->host.name, (int)conn->port); if(server == NULL) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.name, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } ldap_option = LDAP_OPT_X_TLS_HARD; rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } /* rc = ldap_start_tls_s(server, NULL, NULL); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } */ #else /* we should probably never come up to here since configure should check in first place if we can support LDAP SSL/TLS */ failf(data, "LDAP local: SSL/TLS not supported with this version " "of the OpenLDAP toolkit\n"); result = CURLE_SSL_CERTPROBLEM; goto quit; #endif #endif #endif /* CURL_LDAP_USE_SSL */ } else { server = ldap_init(conn->host.name, (int)conn->port); if(server == NULL) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.name, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } } #ifdef CURL_LDAP_WIN ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); #endif rc = ldap_simple_bind_s(server, conn->bits.user_passwd ? conn->user : NULL, conn->bits.user_passwd ? conn->passwd : NULL); if(!ldap_ssl && rc != 0) { ldap_proto = LDAP_VERSION2; ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); rc = ldap_simple_bind_s(server, conn->bits.user_passwd ? conn->user : NULL, conn->bits.user_passwd ? conn->passwd : NULL); } if(rc != 0) { failf(data, "LDAP local: ldap_simple_bind_s %s", ldap_err2string(rc)); result = CURLE_LDAP_CANNOT_BIND; goto quit; } rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope, ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg); if(rc != 0 && rc != LDAP_SIZELIMIT_EXCEEDED) { failf(data, "LDAP remote: %s", ldap_err2string(rc)); result = CURLE_LDAP_SEARCH_FAILED; goto quit; } for(num = 0, entryIterator = ldap_first_entry(server, ldapmsg); entryIterator; entryIterator = ldap_next_entry(server, entryIterator), num++) { BerElement *ber = NULL; char *attribute; /*! suspicious that this isn't 'const' */ char *dn = ldap_get_dn(server, entryIterator); int i; result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4); if(result) goto quit; result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)dn, 0); if(result) goto quit; result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) goto quit; dlsize += strlen(dn)+5; for(attribute = ldap_first_attribute(server, entryIterator, &ber); attribute; attribute = ldap_next_attribute(server, entryIterator, ber)) { BerValue **vals = ldap_get_values_len(server, entryIterator, attribute); if(vals != NULL) { for(i = 0; (vals[i] != NULL); i++) { result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1); if(result) goto quit; result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)attribute, 0); if(result) goto quit; result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)": ", 2); if(result) goto quit; dlsize += strlen(attribute)+3; if((strlen(attribute) > 7) && (strcmp(";binary", (char *)attribute + (strlen((char *)attribute) - 7)) == 0)) { /* Binary attribute, encode to base64. */ CURLcode error = Curl_base64_encode(data, vals[i]->bv_val, vals[i]->bv_len, &val_b64, &val_b64_sz); if(error) { ldap_value_free_len(vals); ldap_memfree(attribute); ldap_memfree(dn); if(ber) ber_free(ber, 0); result = error; goto quit; } if(val_b64_sz > 0) { result = Curl_client_write(conn, CLIENTWRITE_BODY, val_b64, val_b64_sz); free(val_b64); if(result) goto quit; dlsize += val_b64_sz; } } else { result = Curl_client_write(conn, CLIENTWRITE_BODY, vals[i]->bv_val, vals[i]->bv_len); if(result) goto quit; dlsize += vals[i]->bv_len; } result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); if(result) goto quit; dlsize++; } /* Free memory used to store values */ ldap_value_free_len(vals); } result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) goto quit; dlsize++; Curl_pgrsSetDownloadCounter(data, dlsize); ldap_memfree(attribute); } ldap_memfree(dn); if(ber) ber_free(ber, 0); } quit: if(ldapmsg) { ldap_msgfree(ldapmsg); LDAP_TRACE (("Received %d entries\n", num)); } if(rc == LDAP_SIZELIMIT_EXCEEDED) infof(data, "There are more than %d entries\n", num); if(ludp) ldap_free_urldesc(ludp); if(server) ldap_unbind_s(server); #if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK) if(ldap_ssl) ldapssl_client_deinit(); #endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */ /* no data to transfer */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); connclose(conn, "LDAP connection always disable re-use"); return result; }
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; }
handler_t auth_ldap_init(server *srv, mod_auth_plugin_config *s) { #ifdef USE_LDAP int ret; #if 0 if (s->auth_ldap_basedn->used == 0) { log_error_write(srv, __FILE__, __LINE__, "s", "ldap: auth.backend.ldap.base-dn has to be set"); return HANDLER_ERROR; } #endif if (s->auth_ldap_hostname->used) { /* free old context */ if (NULL != s->ldap) ldap_unbind_s(s->ldap); if (NULL == (s->ldap = ldap_init(s->auth_ldap_hostname->ptr, LDAP_PORT))) { log_error_write(srv, __FILE__, __LINE__, "ss", "ldap ...", strerror(errno)); return HANDLER_ERROR; } ret = LDAP_VERSION3; if (LDAP_OPT_SUCCESS != (ret = ldap_set_option(s->ldap, LDAP_OPT_PROTOCOL_VERSION, &ret))) { log_error_write(srv, __FILE__, __LINE__, "ss", "ldap:", ldap_err2string(ret)); return HANDLER_ERROR; } if (s->auth_ldap_starttls) { /* if no CA file is given, it is ok, as we will use encryption * if the server requires a CAfile it will tell us */ if (!buffer_is_empty(s->auth_ldap_cafile)) { if (LDAP_OPT_SUCCESS != (ret = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, s->auth_ldap_cafile->ptr))) { log_error_write(srv, __FILE__, __LINE__, "ss", "Loading CA certificate failed:", ldap_err2string(ret)); return HANDLER_ERROR; } } if (LDAP_OPT_SUCCESS != (ret = ldap_start_tls_s(s->ldap, NULL, NULL))) { log_error_write(srv, __FILE__, __LINE__, "ss", "ldap startTLS failed:", ldap_err2string(ret)); return HANDLER_ERROR; } } /* 1. */ if (s->auth_ldap_binddn->used) { if (LDAP_SUCCESS != (ret = ldap_simple_bind_s(s->ldap, s->auth_ldap_binddn->ptr, s->auth_ldap_bindpw->ptr))) { log_error_write(srv, __FILE__, __LINE__, "ss", "ldap:", ldap_err2string(ret)); return HANDLER_ERROR; } } else { if (LDAP_SUCCESS != (ret = ldap_simple_bind_s(s->ldap, NULL, NULL))) { log_error_write(srv, __FILE__, __LINE__, "ss", "ldap:", ldap_err2string(ret)); return HANDLER_ERROR; } } } return HANDLER_GO_ON; #else UNUSED(s); log_error_write(srv, __FILE__, __LINE__, "s", "no ldap support available"); return HANDLER_ERROR; #endif }
static void ldapconnect(void) { int rc; /* On Windows ldap_start_tls_s is available starting from Windows XP, * so we need to bind at run-time with the function entry point */ #ifdef _SQUID_MSWIN_ if (use_tls) { HMODULE WLDAP32Handle; WLDAP32Handle = GetModuleHandle("wldap32"); if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { fprintf(stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); exit(1); } } #endif if (ld == NULL) { #if HAS_URI_SUPPORT if (strstr(ldapServer, "://") != NULL) { rc = ldap_initialize(&ld, ldapServer); if (rc != LDAP_SUCCESS) { fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); } } else #endif #if NETSCAPE_SSL if (sslpath) { if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", sslpath); exit(1); } else { sslinit++; } if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", ldapServer, port); exit(1); } } else #endif if ((ld = ldap_init(ldapServer, port)) == NULL) { fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); } if (connect_timeout) squid_ldap_set_connect_timeout(connect_timeout); #ifdef LDAP_VERSION3 if (version == -1) { version = LDAP_VERSION2; } if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) != LDAP_SUCCESS) { fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", version); ldap_unbind(ld); ld = NULL; } if (use_tls) { #ifdef LDAP_OPT_X_TLS if ((version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) { fprintf(stderr, "Could not Activate TLS connection\n"); ldap_unbind(ld); ld = NULL; } #else fprintf(stderr, "TLS not supported with your LDAP library\n"); ldap_unbind(ld); ld = NULL; #endif } #endif squid_ldap_set_timelimit(timelimit); squid_ldap_set_referrals(!noreferrals); squid_ldap_set_aliasderef(aliasderef); if (binddn && bindpasswd && *binddn && *bindpasswd) { rc = ldap_simple_bind_s(ld, binddn, bindpasswd); if (rc != LDAP_SUCCESS) { fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); ldap_unbind(ld); ld = NULL; } } if (debug) fprintf(stderr, "Connected OK\n"); } }