Ashwin
Ashwin

Reputation: 1960

LDAP's ldap_search_s() fails on Windows Active Directory

I have setup an Active Directory service on my Windows 2008 server. I have added an user and here is the DN (DistingushedName) CN=ashwin,CN=Users,DC=test,DC=com

There is no password set for the DN and anonymous binds are allowed. I have a sample (test code) C++ program that connects to AD and searches the user.

#include "windows.h"
#include "winldap.h"
#include "stdio.h"

//  Entry point for your application
int main(int argc, char* argv[])
{
    LDAP* pLdapConnection = NULL;
    INT returnCode = 0; 
    INT connectSuccess = 0;
    ULONG version = LDAP_VERSION3;
    LONG lv = 0;
    int option(0);
    LDAPMessage *vLdapMessage;

    //  Initialize an LDAP session without SSL.
    pLdapConnection = ldap_init("192.168.56.128",389);
    if (pLdapConnection == NULL)
    {
        printf( "ldap_init failed with 0x%x.\n",hr);
        return -1;
    }

    //  Specify version 3; the default is version 2.
    returnCode = ldap_set_option(pLdapConnection,
        LDAP_OPT_PROTOCOL_VERSION,
        (void*)&version);
    if (returnCode != LDAP_SUCCESS)
        goto FatalExit;

    //Turning off referrals
    ldap_set_option(pLdapConnection, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); // required 

    //  Connect to the server.
    connectSuccess = ldap_connect(pLdapConnection, NULL);

    if(connectSuccess != LDAP_SUCCESS)
    {
        printf("ldap_connect failed with 0x%x.\n",connectSuccess);
        goto FatalExit;
    }

    //  Bind with current credentials. 
    printf("Binding ...\n");
    returnCode = ldap_bind_s(pLdapConnection,NULL, NULL, LDAP_AUTH_SIMPLE);
    if (returnCode != LDAP_SUCCESS)
        goto FatalExit;

    returnCode = ldap_search_s(pLdapConnection, "DC=test, DC=com", LDAP_SCOPE_SUBTREE, "CN=ashwin", NULL, 0, &vLdapMessage);

    if (returnCode != LDAP_SUCCESS)
        goto FatalExit;

NormalExit:
    if (pLdapConnection != NULL)
        ldap_unbind_s(pLdapConnection);
    return 0;

FatalExit:
    if( pLdapConnection != NULL )
        ldap_unbind_s(pLdapConnection);
    printf( "\n\nERROR: 0x%x\n", returnCode);
    return returnCode;
}

The search fails. ldap_search_s always returns 1. The same setup testing on Apache directory service works fine.

Could someone point why this does not work with Windows AD? what is wrong in the program?

Upvotes: 1

Views: 2979

Answers (1)

X3074861X
X3074861X

Reputation: 3819

Active Directory filtering syntax can be quite verbose. From what I can tell, you just need to modify your filter slightly. Try this :

(&(objectClass=user)(distinguishedName=CN=ashwin,CN=Users,DC=test,DC=com))

However, for single user filtering, I'd try using the sAMAccountName. This generally follows a {FirstInitial}{LastName} format, and would be unique to the user (Ex. JSmith) :

(&(objectClass=user)(sAMAccountName=JSmith))

Upvotes: 2

Related Questions