#include <stdio.h> #include <windows.h> #include <winldap.h> #include <wchar.h> #define AUTH_METHOD LDAP_AUTH_SIMPLE int requested_version = LDAP_VERSION3; int authCheck( char *host, char *port, PWCHAR bind_dn, PWCHAR bind_pw, PWCHAR base); int main(int argc, char **argv); main(int argc, char **argv) { WCHAR oldPassword[128]; if( argc != 5 ) { printf( "Wrong number of arguments!\n" ); printf( "Usage: p4authenticate [IP] [Port] [Domain] [user]\n"); printf( "Example: p4authenticate 1.2.3.4 389 DC=test,DC=perforce,DC=com bob \n"); exit( -1 ); } if(strlen(argv[4]) == 0) { printf("Error: NULL user names are not allowed.\n"); exit (-1); } /* read the password from <stdin> and truncate the newline */ if( fgetws( oldPassword, 128, stdin ) == NULL ) { printf( "Didn't receive old password!\n" ); exit( -1 ); } oldPassword[ wcslen(oldPassword) - 1 ] = '\0'; WCHAR wc_dn[128]; MultiByteToWideChar(CP_UTF8, 0, argv[4], -1, wc_dn, 128); WCHAR wc_base[512]; MultiByteToWideChar(CP_UTF8, 0, argv[3], -1, wc_base, 512); PWCHAR pwc_base = wc_base; PWCHAR pwc_dn = wc_dn; PWCHAR pwop = oldPassword; return( authCheck( argv[1], argv[2], pwc_dn, pwop, pwc_base) ); } int authCheck( char *host, char *port, PWCHAR bind_dn, PWCHAR bind_pw, PWCHAR base) { LDAP *ld; int rc; int portnumber = atoi( port ); /* Get a handle to an LDAP connection. */ if( ( ld = ldap_initA( host, portnumber ) ) == NULL ) { printf( "Can't initialize connection to %s : %d\n" , host, portnumber ); return( -1 ); } ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &requested_version ); /* bind */ rc = ldap_bind_sW( ld, bind_dn, bind_pw, AUTH_METHOD ); /* check result, report errors */ if ( rc != LDAP_SUCCESS ) { if (lstrcmpiA("Invalid credentials", ldap_err2stringA(rc)) == 0) { printf( "Error: Password incorrect (%s).\n", ldap_err2stringA(rc) ); } else { printf("Error: %s.\n",ldap_err2stringA(rc)); } return( -1 ); } LDAPMessage *results, *entry; WCHAR search[1024]; WCHAR *temp = L"(logonName=\0"; struct l_timeval timeout = {10, 0}; wcscat(search, temp); wcscat(search, (const wchar_t *)bind_dn); wcscat(search, L")\0"); PWCHAR psearch = search; rc = ldap_search_ext_sW (ld, base, LDAP_SCOPE_SUBTREE, psearch, NULL, 0, NULL, NULL, &timeout, LDAP_NO_LIMIT, &results ); if(rc != LDAP_SUCCESS) { printf( "Error: Invalid password or no password entered. You must enter a password.\n"); printf( "Error code: (%s).\n", ldap_err2stringA(rc) ); return -1; } printf("Success: Password verified.\n"); ldap_unbind( ld ); return( 0 ); }