/* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */
static void goodG2B()
{
    char * data;
    char dataBuffer[256] = "";
    data = dataBuffer;
    goto source;
source:
    /* FIX: Use a fixed file name */
    strcat(data, "Doe, XXXXX");
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        char filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snprintf(filter, 256-1, "(cn=%s)", data);
        pLdapConnection = ldap_initA("localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sA(
                            pLdapConnection,
                            "base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
Example #2
0
bool AD::Connect()
{
    DWORD ret;
    LONG value;

    //if(!Init())
    //{
    if(!InitSSL())
    {
        Util::Warn(L"Unable to initialize an LDAP context.");
        return false;
    }
    else
    {
        if((ret = ldap_get_option(ldap, LDAP_OPT_SSL, (void *)&value)) != LDAP_SUCCESS)
        {
            Util::Error(LdapGetLastError(), L"ldap_get_option()");
        }
        if((void *)value == LDAP_OPT_ON)
        {
            if((ret = ldap_set_option(ldap, LDAP_OPT_SSL, LDAP_OPT_ON)) != LDAP_SUCCESS)
            {
                Util::Error(LdapGetLastError(), L"ldap_set_option()");
            }
        }
    }
    //}

    if(ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, (void *)LDAP_VERSION3) != LDAP_SUCCESS)
    {
        Util::Error(LdapGetLastError(), L"ldap_set_option()");
        wprintf(L"Ret = %x\n", LdapGetLastError());
    }
    return (ldap_connect(ldap, NULL) == LDAP_SUCCESS) ? true : false;
}
Example #3
0
int _LDAP_initialization(LDAP **ld, PyObject *url) {
	int rc;
	int portnum;
	char *hoststr = NULL;
	const int version = LDAP_VERSION3;
	PyObject *scheme = PyObject_GetAttrString(url, "scheme");
	PyObject *host = PyObject_GetAttrString(url, "host");
	PyObject *port = PyObject_GetAttrString(url, "port");

	if (scheme == NULL || host == NULL || port == NULL) return -1;

	hoststr = PyObject2char(host);
	portnum = PyLong_AsLong(port);
	Py_DECREF(host);
	Py_DECREF(port);

	if (hoststr == NULL) return -1;

	if (PyUnicode_CompareWithASCIIString(scheme, "ldaps") == 0) {
		*ld = ldap_sslinit(hoststr, portnum, 1);
	} else {
		*ld = ldap_init(hoststr, portnum);
	}
	Py_DECREF(scheme);
	if (ld == NULL) return -1;
	ldap_set_option(*ld, LDAP_OPT_PROTOCOL_VERSION, &version);
	rc = ldap_connect(*ld, NULL);
	return rc;
}
void CWE90_LDAP_Injection__w32_wchar_t_environment_21_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[256] = L"";
    data = dataBuffer;
    badStatic = 1; /* true */
    data = badSource(data);
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        wchar_t filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snwprintf(filter, 256-1, L"(cn=%s)", data);
        pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sW(
                            pLdapConnection,
                            L"base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
void CWE90_LDAP_Injection__w32_wchar_t_listen_socket_64b_badSink(void * dataVoidPtr)
{
    /* cast void pointer to a pointer of the appropriate type */
    wchar_t * * dataPtr = (wchar_t * *)dataVoidPtr;
    /* dereference dataPtr into data */
    wchar_t * data = (*dataPtr);
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        wchar_t filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snwprintf(filter, 256-1, L"(cn=%s)", data);
        pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sW(
                            pLdapConnection,
                            L"base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
void badSink(vector<char *> dataVector)
{
    /* copy data out of dataVector */
    char * data = dataVector[2];
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        char filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snprintf(filter, 256-1, "(cn=%s)", data);
        pLdapConnection = ldap_initA("localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sA(
                            pLdapConnection,
                            "base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
Example #7
0
/* -1 if trouble
   0 if user is NOT member of current server group
   1 if user IS MEMBER of current server group 
 */
int ldap_ismember(ldap_opt_t * l, const char * user) {
    LDAPMessage *res;
    char * filter;
    int i;

    if ((!l->sgroup) || !(l->g_basedn))
        return 1;

    /* Am i still connected ? RETRY n times */
    /* XXX TODO: setup some conf value for retrying */
    if (!(l->flags & FLAG_CONNECTED)) 
        for (i = 0 ; i < 2 ; i++)
            if (ldap_connect(l) == 0)
                 break;

    /* quick check for attempts to be evil */
    if ((strchr(user, '(') != NULL) || (strchr(user, ')') != NULL) ||
        (strchr(user, '*') != NULL) || (strchr(user, '\\') != NULL))
        return FAILURE;

    /* build filter for LDAP request */
    REQUEST_GROUP(filter, l->fgroup, user);

    if (ldap_search_st( l->ld, 
        l->g_basedn,
        LDAP_SCOPE_SUBTREE,
        filter,
        NULL, 0, &l->s_timeout, &res) != LDAP_SUCCESS) {
    
        ldap_perror(l->ld, "ldap_search_st()");

        free(filter);

        /* XXX error on search, timeout etc.. close ask for reconnect */
        ldap_close(l);

        return FAILURE;
    }

    free(filter);

    /* check if any results */
    if (ldap_count_entries(l->ld, res) > 0) {
        ldap_msgfree(res);
        return 1;
    }

    ldap_msgfree(res);
    return 0;
}
Example #8
0
static int
ldap_open(void)
{
	struct aldap_message	*amsg = NULL;

	aldap = ldap_connect(url);
	if (aldap == NULL) {
		log_warnx("warn: table-ldap: ldap_connect error");
		goto err;
	}

	if (aldap_bind(aldap, username, password) == -1) {
		log_warnx("warn: table-ldap: aldap_bind error");
		goto err;
	}

	if ((amsg = aldap_parse(aldap)) == NULL) {
		log_warnx("warn: table-ldap: aldap_parse");
		goto err;
	}

	switch (aldap_get_resultcode(amsg)) {
	case LDAP_SUCCESS:
		log_debug("debug: table-ldap: ldap server accepted credentials");
		break;
	case LDAP_INVALID_CREDENTIALS:
		log_warnx("warn: table-ldap: ldap server refused credentials");
		goto err;
	default:
		log_warnx("warn: table-ldap: failed to bind, result #%d",
		    aldap_get_resultcode(amsg));
		goto err;
	}

	if (amsg)
		aldap_freemsg(amsg);
	return (1);

err:
	if (aldap)
		aldap_close(aldap);
	if (amsg)
		aldap_freemsg(amsg);
	return (0);
}
Example #9
0
int _LDAP_initialization(LDAP **ld, PyObject *url, int tls_option) {
	int rc;
	int portnum;
	char *hoststr = NULL;
	const int version = LDAP_VERSION3;
	const int tls_settings = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_SERVERNAME_CHECK;
	PyObject *scheme = PyObject_GetAttrString(url, "scheme");
	PyObject *host = PyObject_GetAttrString(url, "host");
	PyObject *port = PyObject_GetAttrString(url, "port");

	if (scheme == NULL || host == NULL || port == NULL) return -1;

	hoststr = PyObject2char(host);
	portnum = PyLong_AsLong(port);
	Py_DECREF(host);
	Py_DECREF(port);

	if (hoststr == NULL) return -1;

	if (PyUnicode_CompareWithASCIIString(scheme, "ldaps") == 0) {
		*ld = ldap_sslinit(hoststr, portnum, 1);
	} else {
		*ld = ldap_init(hoststr, portnum);
	}
	Py_DECREF(scheme);
	if (ld == NULL) return -1;
	ldap_set_option(*ld, LDAP_OPT_PROTOCOL_VERSION, &version);
	switch (tls_option) {
		case -1:
			/* Cert policy is not set, nothing to do.*/
			break;
		case 2:
		case 4:
			/* Cert policy is demand or try, then standard procedure. */
			break;
		case 0:
		case 3:
			/* Cert policy is never or allow, then set TLS settings. */
			ldap_set_option(*ld, 0x43, &tls_settings);
			ldap_set_option(*ld, LDAP_OPT_SERVER_CERTIFICATE, &noverify);
			break;
	}
	rc = ldap_connect(*ld, NULL);
	return rc;
}
Example #10
0
void AD::GetDN()
{
    LPWSTR filters[2];
    LDAPMessage *search;
    LDAPMessage *entry;
    PWCHAR attribute;
    PWCHAR *value;
    BerElement *berElement;

    filters[0] = L"rootDomainNamingContext";
    filters[1] = NULL;

    ldap = ldap_init((PWCHAR)host.c_str(), LDAP_PORT);
    // Null binding; to do that we simply do not call ldap_bind.

    if(ldap_connect(ldap, NULL) != LDAP_SUCCESS)
    {
        Util::Error(LdapGetLastError(), L"ldap_connect()");
        wprintf(L"Ret = %x\n", LdapGetLastError());
    }
    if(ldap_search_s(ldap, L"", LDAP_SCOPE_BASE, L"(&(objectClass=*))", filters, 0, &search) != LDAP_SUCCESS)
    {
        Util::Error(LdapGetLastError(), L"ldap_search_s()");
        wprintf(L"Ret= %x\n", LdapGetLastError());
    }
    entry = ldap_first_entry(ldap, search);
    attribute = ldap_first_attribute(ldap, entry, &berElement);

    if(lstrcmpi(L"rootDomainNamingContext", attribute) == 0)
    {
        value = ldap_get_values(ldap, entry, attribute);
        wprintf(L"value = %s\n", value[0]);
        dn = value[0];
    }
    else
    {
        dn.clear();
    }
    ldap_value_free(value);
    ldap_memfree(attribute);
    ldap_msgfree(search);
    ber_free(berElement, 0);
}
Example #11
0
int ldap_reconnect(char* _ld_name)
{
	int rc;
	
	if (ldap_disconnect(_ld_name) != 0)
	{
		LM_ERR("[%s]: disconnect failed\n", _ld_name);
		return -1;
	}

	if ((rc = ldap_connect(_ld_name)) != 0)
	{
		LM_ERR("[%s]: reconnect failed\n",
				_ld_name);
	}
	else
	{
		LM_ERR("[%s]: LDAP reconnect successful\n",
				_ld_name);
	}
	return rc;
}
Example #12
0
static int child_init(int rank)
{
	int i = 0, ld_count = 0;
	char* ld_name;

	/* don't do anything for non-worker process */
	if (rank==PROC_MAIN || rank==PROC_TCP_MAIN) {
		return 0;
	}

	/*
	* build ld_sessions and connect all sessions
	*/
	ld_count = iniparser_getnsec(config_vals);
	for (i = 0; i < ld_count; i++)
	{
		ld_name = iniparser_getsecname(config_vals, i);
		if (add_ld_session(ld_name,
					NULL,
					config_vals)
				!= 0)
		{
			LM_ERR("[%s]: add_ld_session failed\n", ld_name);
			return -1;
		}

		if (ldap_connect(ld_name) != 0)
		{
			LM_ERR("[%s]: failed to connect to LDAP host(s)\n", ld_name);
			ldap_disconnect(ld_name);
			return -1;
		}

	}

	return 0;
}
void CWE90_LDAP_Injection__w32_wchar_t_listen_socket_12_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[256] = L"";
    data = dataBuffer;
    if(globalReturnsTrueOrFalse())
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            wchar_t *replace;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            size_t dataLen = wcslen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (256 - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
                /* Eliminate CRLF */
                replace = wcschr(data, L'\r');
                if (replace)
                {
                    *replace = L'\0';
                }
                replace = wcschr(data, L'\n');
                if (replace)
                {
                    *replace = L'\0';
                }
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    else
    {
        /* FIX: Use a fixed file name */
        wcscat(data, L"Doe, XXXXX");
    }
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        wchar_t filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snwprintf(filter, 256-1, L"(cn=%s)", data);
        pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sW(
                            pLdapConnection,
                            L"base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
/* goodG2B1() - use goodsource and badsink by changing the staticFive==5 to staticFive!=5 */
static void goodG2B1()
{
    wchar_t * data;
    wchar_t dataBuffer[256] = L"";
    data = dataBuffer;
    if(staticFive!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Use a fixed file name */
        wcscat(data, L"Doe, XXXXX");
    }
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        wchar_t filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snwprintf(filter, 256-1, L"(cn=%s)", data);
        pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sW(
                            pLdapConnection,
                            L"base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
void CWE90_LDAP_Injection__w32_wchar_t_environment_12_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[256] = L"";
    data = dataBuffer;
    if(globalReturnsTrueOrFalse())
    {
        {
            /* Append input from an environment variable to data */
            size_t dataLen = wcslen(data);
            wchar_t * environment = GETENV(ENV_VARIABLE);
            /* If there is data in the environment variable */
            if (environment != NULL)
            {
                /* POTENTIAL FLAW: Read data from an environment variable */
                wcsncat(data+dataLen, environment, 256-dataLen-1);
            }
        }
    }
    else
    {
        /* FIX: Use a fixed file name */
        wcscat(data, L"Doe, XXXXX");
    }
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        wchar_t filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snwprintf(filter, 256-1, L"(cn=%s)", data);
        pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sW(
                            pLdapConnection,
                            L"base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
void CWE90_LDAP_Injection__w32_char_connect_socket_08_bad()
{
    char * data;
    char dataBuffer[256] = "";
    data = dataBuffer;
    if(staticReturnsTrue())
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            char *replace;
            SOCKET connectSocket = INVALID_SOCKET;
            size_t dataLen = strlen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a connect socket */
                connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (connectSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
                service.sin_port = htons(TCP_PORT);
                if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed, make sure to recv one
                 * less char than is in the recv_buf in order to append a terminator */
                /* Abort on error or the connection was closed */
                recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (256 - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(char)] = '\0';
                /* Eliminate CRLF */
                replace = strchr(data, '\r');
                if (replace)
                {
                    *replace = '\0';
                }
                replace = strchr(data, '\n');
                if (replace)
                {
                    *replace = '\0';
                }
            }
            while (0);
            if (connectSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(connectSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        char filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snprintf(filter, 256-1, "(cn=%s)", data);
        pLdapConnection = ldap_initA("localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sA(
                            pLdapConnection,
                            "base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
Example #17
0
/*%
 * This function is the real core of the driver.   Zone, record
 * and client strings are passed in (or NULL is passed if the
 * string is not available).  The type of query we want to run
 * is indicated by the query flag, and the dbdata object is passed
 * passed in to.  dbdata really holds either:
 *		1) a list of database instances (in multithreaded mode) OR
 *		2) a single database instance (in single threaded mode)
 * The function will construct the query and obtain an available
 * database instance (DBI).  It will then run the query and hopefully
 * obtain a result set.
 */
static isc_result_t
ldap_get_results(const char *zone, const char *record,
		 const char *client, unsigned int query,
		 void *dbdata, void *ptr)
{
	isc_result_t result;
	ldap_instance_t *db = (ldap_instance_t *)dbdata;
	dbinstance_t *dbi = NULL;
	char *querystring = NULL;
	LDAPURLDesc *ldap_url = NULL;
	int ldap_result = 0;
	LDAPMessage *ldap_msg = NULL;
	int i;
	int entries;

	/* get db instance / connection */
#if PTHREADS
	/* find an available DBI from the list */
	dbi = ldap_find_avail_conn(db);
#else /* PTHREADS */
	/*
	 * only 1 DBI - no need to lock instance lock either
	 * only 1 thread in the whole process, no possible contention.
	 */
	dbi = (dbinstance_t *)(db->db);
#endif /* PTHREADS */

	/* if DBI is null, can't do anything else */
	if (dbi == NULL)
		return (ISC_R_FAILURE);

	/* set fields */
	if (zone != NULL) {
		dbi->zone = strdup(zone);
		if (dbi->zone == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
	} else
		dbi->zone = NULL;

	if (record != NULL) {
		dbi->record = strdup(record);
		if (dbi->record == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
	} else
		dbi->record = NULL;

	if (client != NULL) {
		dbi->client = strdup(client);
		if (dbi->client == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
	} else
		dbi->client = NULL;


	/* what type of query are we going to run? */
	switch (query) {
	case ALLNODES:
		/*
		 * if the query was not passed in from the config file
		 * then we can't run it.  return not_implemented, so
		 * it's like the code for that operation was never
		 * built into the driver.... AHHH flexibility!!!
		 */
		if (dbi->allnodes_q == NULL) {
			result = ISC_R_NOTIMPLEMENTED;
			goto cleanup;
		} else
			querystring = build_querystring(dbi->allnodes_q);
		break;
	case ALLOWXFR:
		/* same as comments as ALLNODES */
		if (dbi->allowxfr_q == NULL) {
			result = ISC_R_NOTIMPLEMENTED;
			goto cleanup;
		} else
			querystring = build_querystring(dbi->allowxfr_q);
		break;
	case AUTHORITY:
		/* same as comments as ALLNODES */
		if (dbi->authority_q == NULL) {
			result = ISC_R_NOTIMPLEMENTED;
			goto cleanup;
		} else
			querystring = build_querystring(dbi->authority_q);
		break;
	case FINDZONE:
		/* this is required.  It's the whole point of DLZ! */
		if (dbi->findzone_q == NULL) {
			db->log(ISC_LOG_DEBUG(2),
				"No query specified for findzone. "
				"Findzone requires a query");
			result = ISC_R_FAILURE;
			goto cleanup;
		} else
			querystring = build_querystring(dbi->findzone_q);
		break;
	case LOOKUP:
		/* this is required.  It's also a major point of DLZ! */
		if (dbi->lookup_q == NULL) {
			db->log(ISC_LOG_DEBUG(2),
				"No query specified for lookup. "
				"Lookup requires a query");
			result = ISC_R_FAILURE;
			goto cleanup;
		} else
			querystring = build_querystring(dbi->lookup_q);
		break;
	default:
		/*
		 * this should never happen.  If it does, the code is
		 * screwed up!
		 */
		db->log(ISC_LOG_ERROR,
			"Incorrect query flag passed to ldap_get_results");
		result = ISC_R_UNEXPECTED;
		goto cleanup;
	}

	/* if the querystring is null, Bummer, outta RAM.  UPGRADE TIME!!!   */
	if (querystring  == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}

	/*
	 * output the full query string during debug so we can see
	 * what lame error the query has.
	 */
	db->log(ISC_LOG_DEBUG(1), "Query String: %s", querystring);

	/* break URL down into it's component parts, if error cleanup */
	ldap_result = ldap_url_parse(querystring, &ldap_url);
	if (ldap_result != LDAP_SUCCESS || ldap_url == NULL) {
		result = ISC_R_FAILURE;
		goto cleanup;
	}

	for (i = 0; i < 3; i++) {
		/*
		 * dbi->dbconn may be null if trying to reconnect on a
		 * previous query failed.
		 */
		if (dbi->dbconn == NULL) {
			db->log(ISC_LOG_INFO,
				"LDAP driver attempting to re-connect");

			result = ldap_connect((ldap_instance_t *) dbdata, dbi);
			if (result != ISC_R_SUCCESS) {
				result = ISC_R_FAILURE;
				continue;
			}
		}

		/* perform ldap search syncronously */
		ldap_result = ldap_search_s((LDAP *) dbi->dbconn,
					    ldap_url->lud_dn,
					    ldap_url->lud_scope,
					    ldap_url->lud_filter,
					    ldap_url->lud_attrs, 0, &ldap_msg);

		/*
		 * check return code.  No such object is ok, just
		 * didn't find what we wanted
		 */
		switch (ldap_result) {
		case LDAP_NO_SUCH_OBJECT:
    			db->log(ISC_LOG_DEBUG(1),
				"No object found matching query requirements");
			result = ISC_R_NOTFOUND;
			goto cleanup;
			break;
		case LDAP_SUCCESS:	/* on success do nothing */
			result = ISC_R_SUCCESS;
			i = 3;
			break;
		case LDAP_SERVER_DOWN:
			db->log(ISC_LOG_INFO,
				"LDAP driver attempting to re-connect");
			result = ldap_connect((ldap_instance_t *) dbdata, dbi);
			if (result != ISC_R_SUCCESS)
				result = ISC_R_FAILURE;
			break;
		default:
			/*
			 * other errors not ok.  Log error message and
			 * get out
			 */
    			db->log(ISC_LOG_ERROR, "LDAP error: %s",
				ldap_err2string(ldap_result));
			result = ISC_R_FAILURE;
			goto cleanup;
			break;
		}
	}

	if (result != ISC_R_SUCCESS)
		goto cleanup;

	switch (query) {
	case ALLNODES:
		result = ldap_process_results(db, (LDAP *) dbi->dbconn,
					      ldap_msg, ldap_url->lud_attrs,
					      ptr, ISC_TRUE);
		break;
	case AUTHORITY:
	case LOOKUP:
		result = ldap_process_results(db, (LDAP *) dbi->dbconn,
					      ldap_msg, ldap_url->lud_attrs,
					      ptr, ISC_FALSE);
		break;
	case ALLOWXFR:
		entries = ldap_count_entries((LDAP *) dbi->dbconn, ldap_msg);
		if (entries == 0)
			result = ISC_R_NOPERM;
		else if (entries > 0)
			result = ISC_R_SUCCESS;
		else
			result = ISC_R_FAILURE;
		break;
	case FINDZONE:
		entries = ldap_count_entries((LDAP *) dbi->dbconn, ldap_msg);
		if (entries == 0)
			result = ISC_R_NOTFOUND;
		else if (entries > 0)
			result = ISC_R_SUCCESS;
		else
			result = ISC_R_FAILURE;
		break;
	default:
		/*
		 * this should never happen.  If it does, the code is
		 * screwed up!
		 */
		db->log(ISC_LOG_ERROR,
			"Incorrect query flag passed to ldap_get_results");
		result = ISC_R_UNEXPECTED;
	}

 cleanup:
	/* it's always good to cleanup after yourself */

	/* if we retrieved results, free them */
	if (ldap_msg != NULL)
		ldap_msgfree(ldap_msg);

	if (ldap_url != NULL)
		ldap_free_urldesc(ldap_url);

	/* cleanup */
	if (dbi->zone != NULL)
		free(dbi->zone);
	if (dbi->record != NULL)
		free(dbi->record);
	if (dbi->client != NULL)
		free(dbi->client);
	dbi->zone = dbi->record = dbi->client = NULL;

	/* release the lock so another thread can use this dbi */
	(void) dlz_mutex_unlock(&dbi->lock);

	/* release query string */
	if (querystring != NULL)
		free(querystring);

	/* return result */
	return (result);
}
void CWE90_LDAP_Injection__w32_char_console_14_bad()
{
    char * data;
    char dataBuffer[256] = "";
    data = dataBuffer;
    if(globalFive==5)
    {
        {
            /* Read input from the console */
            size_t dataLen = strlen(data);
            /* if there is room in data, read into it from the console */
            if (256-dataLen > 1)
            {
                /* POTENTIAL FLAW: Read data from the console */
                if (fgets(data+dataLen, (int)(256-dataLen), stdin) != NULL)
                {
                    /* The next few lines remove the carriage return from the string that is
                     * inserted by fgets() */
                    dataLen = strlen(data);
                    if (dataLen > 0 && data[dataLen-1] == '\n')
                    {
                        data[dataLen-1] = '\0';
                    }
                }
                else
                {
                    printLine("fgets() failed");
                    /* Restore NUL terminator if fgets fails */
                    data[dataLen] = '\0';
                }
            }
        }
    }
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        char filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snprintf(filter, 256-1, "(cn=%s)", data);
        pLdapConnection = ldap_initA("localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sA(
                            pLdapConnection,
                            "base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
void CWE90_LDAP_Injection__w32_wchar_t_file_10_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[256] = L"";
    data = dataBuffer;
    if(globalTrue)
    {
        {
            /* Read input from a file */
            size_t dataLen = wcslen(data);
            FILE * pFile;
            /* if there is room in data, attempt to read the input from a file */
            if (256-dataLen > 1)
            {
                pFile = fopen(FILENAME, "r");
                if (pFile != NULL)
                {
                    /* POTENTIAL FLAW: Read data from a file */
                    if (fgetws(data+dataLen, (int)(256-dataLen), pFile) == NULL)
                    {
                        printLine("fgetws() failed");
                        /* Restore NUL terminator if fgetws fails */
                        data[dataLen] = L'\0';
                    }
                    fclose(pFile);
                }
            }
        }
    }
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        wchar_t filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snwprintf(filter, 256-1, L"(cn=%s)", data);
        pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sW(
                            pLdapConnection,
                            L"base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
Example #20
0
isc_result_t
dlz_create(const char *dlzname, unsigned int argc, char *argv[],
	   void **dbdata, ...)
{
	isc_result_t result = ISC_R_FAILURE;
	ldap_instance_t *ldap = NULL;
	dbinstance_t *dbi = NULL;
	const char *helper_name;
	int protocol;
	int method;
#if PTHREADS
	int dbcount;
	char *endp;
	int i;
#endif /* PTHREADS */
	va_list ap;

	UNUSED(dlzname);

	/* allocate memory for LDAP instance */
	ldap = calloc(1, sizeof(ldap_instance_t));
	if (ldap == NULL)
		return (ISC_R_NOMEMORY);
	memset(ldap, 0, sizeof(ldap_instance_t));

	/* Fill in the helper functions */
	va_start(ap, dbdata);
	while ((helper_name = va_arg(ap, const char*)) != NULL)
		b9_add_helper(ldap, helper_name, va_arg(ap, void*));
	va_end(ap);

#if PTHREADS
	/* if debugging, let user know we are multithreaded. */
	ldap->log(ISC_LOG_DEBUG(1), "LDAP driver running multithreaded");
#else /* PTHREADS */
	/* if debugging, let user know we are single threaded. */
	ldap->log(ISC_LOG_DEBUG(1), "LDAP driver running single threaded");
#endif /* PTHREADS */

	if (argc < 9) {
		ldap->log(ISC_LOG_ERROR,
			  "LDAP driver requires at least "
			  "8 command line args.");
		goto cleanup;
	}

	/* no more than 13 arg's should be passed to the driver */
	if (argc > 12) {
		ldap->log(ISC_LOG_ERROR,
			  "LDAP driver cannot accept more than "
			  "11 command line args.");
		goto cleanup;
	}

	/* determine protocol version. */
	if (strncasecmp(argv[2], V2, strlen(V2)) == 0)
		protocol = 2;
	else if (strncasecmp(argv[2], V3, strlen(V3)) == 0)
		protocol = 3;
	else {
		ldap->log(ISC_LOG_ERROR,
			  "LDAP driver protocol must be either %s or %s",
			  V2, V3);
		goto cleanup;
	}

	/* determine connection method. */
	if (strncasecmp(argv[3], SIMPLE, strlen(SIMPLE)) == 0)
		method = LDAP_AUTH_SIMPLE;
	else if (strncasecmp(argv[3], KRB41, strlen(KRB41)) == 0)
		method = LDAP_AUTH_KRBV41;
	else if (strncasecmp(argv[3], KRB42, strlen(KRB42)) == 0)
		method = LDAP_AUTH_KRBV42;
	else {
		ldap->log(ISC_LOG_ERROR,
			  "LDAP driver authentication method must be "
			  "one of %s, %s or %s", SIMPLE, KRB41, KRB42);
		goto cleanup;
	}

	/* multithreaded build can have multiple DB connections */
#if PTHREADS
	/* check how many db connections we should create */
	dbcount = strtol(argv[1], &endp, 10);
	if (*endp != '\0' || dbcount < 0) {
		ldap->log(ISC_LOG_ERROR,
			  "LDAP driver database connection count "
			  "must be positive.");
		goto cleanup;
	}
#endif

	/* check that LDAP URL parameters make sense */
	switch (argc) {
	case 12:
		result = ldap_checkURL(ldap, argv[11], 0,
				       "allow zone transfer");
		if (result != ISC_R_SUCCESS)
			goto cleanup;
	case 11:
		result = ldap_checkURL(ldap, argv[10], 3, "all nodes");
		if (result != ISC_R_SUCCESS)
			goto cleanup;
	case 10:
		if (strlen(argv[9]) > 0) {
			result = ldap_checkURL(ldap, argv[9], 3, "authority");
			if (result != ISC_R_SUCCESS)
				goto cleanup;
		}
	case 9:
		result = ldap_checkURL(ldap, argv[8], 3, "lookup");
		if (result != ISC_R_SUCCESS)
			goto cleanup;
		result = ldap_checkURL(ldap, argv[7], 0, "find zone");
		if (result != ISC_R_SUCCESS)
			goto cleanup;
		break;
	default:
		/* not really needed, should shut up compiler. */
		result = ISC_R_FAILURE;
	}

	/* store info needed to automatically re-connect. */
	ldap->protocol = protocol;
	ldap->method = method;
	ldap->hosts = strdup(argv[6]);
	if (ldap->hosts == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}
	ldap->user = strdup(argv[4]);
	if (ldap->user == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}
	ldap->cred = strdup(argv[5]);
	if (ldap->cred == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}

#if PTHREADS
	/* allocate memory for database connection list */
	ldap->db = calloc(1, sizeof(db_list_t));
	if (ldap->db == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}

	/* initialize DB connection list */
	DLZ_LIST_INIT(*(ldap->db));

	/*
	 * create the appropriate number of database instances (DBI)
	 * append each new DBI to the end of the list
	 */
	for (i = 0; i < dbcount; i++) {
#endif /* PTHREADS */
		/* how many queries were passed in from config file? */
		switch (argc) {
		case 9:
			result = build_dbinstance(NULL, NULL, NULL, argv[7],
						  argv[8], NULL, &dbi,
						  ldap->log);
			break;
		case 10:
			result = build_dbinstance(NULL, NULL, argv[9],
						  argv[7], argv[8],
						  NULL, &dbi, ldap->log);
			break;
		case 11:
			result = build_dbinstance(argv[10], NULL, argv[9],
						  argv[7], argv[8],
						  NULL, &dbi, ldap->log);
			break;
		case 12:
			result = build_dbinstance(argv[10], argv[11],
						  argv[9], argv[7],
						  argv[8], NULL, &dbi,
						  ldap->log);
			break;
		default:
			/* not really needed, should shut up compiler. */
			result = ISC_R_FAILURE;
		}

		if (result == ISC_R_SUCCESS) {
			ldap->log(ISC_LOG_DEBUG(2),
				  "LDAP driver created "
				  "database instance object.");
		} else { /* unsuccessful?, log err msg and cleanup. */
			ldap->log(ISC_LOG_ERROR,
				  "LDAP driver could not create "
				  "database instance object.");
			goto cleanup;
		}

#if PTHREADS
		/* when multithreaded, build a list of DBI's */
		DLZ_LINK_INIT(dbi, link);
		DLZ_LIST_APPEND(*(ldap->db), dbi, link);
#else
		/*
		 * when single threaded, hold onto the one connection
		 * instance.
		 */
		ldap->db = dbi;
#endif
		/* attempt to connect */
		result = ldap_connect(ldap, dbi);

		/*
		 * if db connection cannot be created, log err msg and
		 * cleanup.
		 */
		switch (result) {
			/* success, do nothing */
		case ISC_R_SUCCESS:
			break;
			/*
			 * no memory means ldap_init could not
			 * allocate memory
			 */
		case ISC_R_NOMEMORY:
#if PTHREADS
			ldap->log(ISC_LOG_ERROR,
				  "LDAP driver could not allocate memory "
				  "for connection number %u", i + 1);
#else
			ldap->log(ISC_LOG_ERROR,
				  "LDAP driver could not allocate memory "
				  "for connection");
#endif
			goto cleanup;
			/*
			 * no perm means ldap_set_option could not set
			 * protocol version
			 */
		case ISC_R_NOPERM:
			ldap->log(ISC_LOG_ERROR,
				  "LDAP driver could not "
				  "set protocol version.");
			result = ISC_R_FAILURE;
			goto cleanup;
			/* failure means couldn't connect to ldap server */
		case ISC_R_FAILURE:
#if PTHREADS
			ldap->log(ISC_LOG_ERROR,
				  "LDAP driver could not bind "
				  "connection number %u to server.", i + 1);
#else
			ldap->log(ISC_LOG_ERROR,
				  "LDAP driver could not "
				  "bind connection to server.");
#endif
			goto cleanup;
			/*
			 * default should never happen.  If it does,
			 * major errors.
			 */
		default:
			ldap->log(ISC_LOG_ERROR,
				  "dlz_create() failed (%d)", result);
			result = ISC_R_UNEXPECTED;
			goto cleanup;
		}

#if PTHREADS
		/* set DBI = null for next loop through. */
		dbi = NULL;
	}
#endif /* PTHREADS */

	/* set dbdata to the ldap_instance we created. */
	*dbdata = ldap;

	return (ISC_R_SUCCESS);

 cleanup:
	dlz_destroy(ldap);

	return (result);
}
Example #21
0
STDMETHODIMP CLDAPQuery::connect(
	/* [in] */ BSTR username,
	/* [in] */ BSTR password,
	/* [in] */ BSTR host,
	/* [in] */ VARIANT_BOOL usessl,
	/* [retval][out] */ LONG *connect_id)
{
	m_errorCode = 0L;
	const ULONG no_limit = LDAP_NO_LIMIT;

	PLDAP ld = NULL;
	bool useSSL = (usessl==VARIANT_TRUE)? true : false;
	bool canFindFromRoot = true;
	CAttributesSchema *attrsSchema = NULL;
	ULONG ulPort = useSSL?LDAP_SSL_PORT:LDAP_PORT;
	
	PTCHAR port = NULL;
	CString defaultNamingContext;
	CString csHost = host;
	CString hostname = _tcstok_s(csHost.GetBuffer(), _T(":"), &port);
	if(port && _tcslen(port) > 0)
		ulPort = _tcstol(port, NULL, 10);
	csHost.ReleaseBuffer();

	try
	{
		if (useSSL)
		{
			if((ld = ldap_sslinit(hostname.GetBuffer(), ulPort, 1))==NULL)
			{
				m_errorCode = LdapGetLastError();
				return S_FALSE;
			}

			m_errorCode = ldap_set_option(ld, LDAP_OPT_SERVER_CERTIFICATE, &CertRoutine);
			if (m_errorCode != LDAP_SUCCESS)
				throw _T("error LDAP_OPT_SERVER_CERTIFICATE");
		}
		else
		{
			if((ld = ldap_init(hostname.GetBuffer(), ulPort))==NULL)
			{
				m_errorCode = LdapGetLastError();
				return S_FALSE;
			}
		}

		const ULONG version = LDAP_VERSION3;
		m_errorCode = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, (void*)&version);
		if (m_errorCode != LDAP_SUCCESS)
			throw _T("error LDAP_OPT_PROTOCOL_VERSION");

		m_errorCode = ldap_set_option(ld, LDAP_OPT_SIZELIMIT, (void*)&no_limit);
		if (m_errorCode != LDAP_SUCCESS)
			throw _T("error LDAP_OPT_SIZELIMIT");
		ld->ld_sizelimit = no_limit;

		m_errorCode = ldap_set_option(ld, LDAP_OPT_TIMELIMIT, (void*)&no_limit);
		if (m_errorCode != LDAP_SUCCESS)
			throw _T("error LDAP_OPT_TIMELIMIT");
		ld->ld_timelimit = no_limit;

		m_errorCode = ldap_connect(ld, 0);
		if (m_errorCode != LDAP_SUCCESS )
			throw _T("error ldap_connect");

		m_errorCode = ldap_bind_s(ld, CString(username).GetBuffer(), CString(password).GetBuffer(), LDAP_AUTH_SIMPLE);
		if (m_errorCode != LDAP_SUCCESS)
			throw _T("error LDAP_AUTH_SIMPLE");

		/* Get the RootDSE and BaseDN attribute (add checks on use this code).*/
		CSimpleArray<PTCHAR> a;
		a.Add(_T("defaultNamingContext"));
		a.Add(_T("subschemaSubentry"));
		a.Add(NULL);
		PLDAPMessage pBaseMsg = NULL;
		if(ldap_search_s(ld, _T(""), LDAP_SCOPE_BASE, _T("(objectClass=*)"), a.GetData(), 0, &pBaseMsg) == LDAP_SUCCESS)
		{
			PLDAPMessage const entry = ldap_first_entry(ld, pBaseMsg);
			if(entry)
			{
				PTCHAR * const pschema = ldap_get_values(ld, entry, _T("subschemaSubentry"));
				if(pschema)
				{
					attrsSchema = new CAttributesSchema(ld, *pschema);
					ldap_value_free(pschema);
				}
				//try to find one item in subtree from root, if found it is Global Catalog search
				PLDAPSearch const pPages = ldap_search_init_page(ld, NULL, LDAP_SCOPE_SUBTREE, _T("(objectClass=*)"), NULL, 0, NULL, NULL, no_limit, 1, NULL);
				if(pPages)
				{
					PLDAPMessage pMsg = NULL;
					canFindFromRoot = (ldap_get_next_page_s(ld, pPages, NULL, 1, NULL, &pMsg) == LDAP_SUCCESS);
					if(pMsg)
						ldap_msgfree(pMsg);
					ldap_search_abandon_page(ld, pPages);
				}
				PTCHAR * const pDefaultNamingContext = ldap_get_values(ld, entry, _T("defaultNamingContext"));
				if(pDefaultNamingContext)
				{
					defaultNamingContext = *pDefaultNamingContext;
					ldap_value_free(pDefaultNamingContext);
				}
			}
			ldap_msgfree(pBaseMsg);
		}

		ÑConnectInfo * const cinfo = new ÑConnectInfo(ld, attrsSchema, defaultNamingContext, canFindFromRoot);
		*connect_id = ++m_maxConnectionId;
		m_connections.Add(*connect_id, cinfo);
	}
	catch (PTCHAR /*e*/)
	{
		if (ld)
			ldap_unbind_s(ld);
		*connect_id = -1;
		return S_FALSE;
	}
	
	return S_OK;
}
Example #22
0
//----------------------------------------------------------------------------
//
//  RestoreDeletedObject()
//
//  Restores a deleted object. 
//
//  pwszDeletedDN - Contains the fully-qualified distinguished name of the 
//  deleted object.
//
//  pwszDestContainerDN - Contains the fully-qualified distinguished name of 
//  the folder that the delted object should be moved to.
//
//  Returns S_OK if successful or an HRESULT or LDAP error code otherwise.
//
//----------------------------------------------------------------------------
HRESULT RestoreDeletedObject(LPCWSTR pwszDeletedDN, LPCWSTR pwszDestContainerDN)
{
    if((NULL == pwszDeletedDN) || (NULL == pwszDestContainerDN))
    {
        return E_POINTER;
    }
    
    HRESULT hr = E_FAIL;

    // Build the new distinguished name.
    LPWSTR pwszNewDN = new WCHAR[lstrlenW(pwszDeletedDN) + lstrlenW(pwszDestContainerDN) + 1];
    if(pwszNewDN)
    {
        lstrcpyW(pwszNewDN, pwszDeletedDN);

        // Search for the first 0x0A character. This is the delimiter in the deleted object name.
        LPWSTR pwszChar;
        for(pwszChar = pwszNewDN; *pwszChar; pwszChar = CharNextW(pwszChar))
        {
            if(('\\' == *pwszChar) && ('0' == *(pwszChar + 1)) && ('A' == *(pwszChar + 2)))
            {
                break;
            }
            
        }

        if(0 != *pwszChar)
        {
            // Truncate the name string at the delimiter.
            *pwszChar = 0;

            // Add the last known parent DN to complete the DN.
            lstrcatW(pwszNewDN, L",");
            lstrcatW(pwszNewDN, pwszDestContainerDN);

            PLDAP	ld;

            // Initialize LDAP.
            ld = ldap_init(NULL, LDAP_PORT);
            if(NULL != ld) 
            {
                ULONG ulRC;
                ULONG version = LDAP_VERSION3;

                // Set the LDAP version.
                ulRC = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, (void*)&version);
                if(LDAP_SUCCESS == ulRC)
                {
                    // Establish a connection with the server.
                    ulRC = ldap_connect(ld, NULL);
                    if(LDAP_SUCCESS == ulRC)
                    {                    
                        // Bind to the LDAP server.
                        ulRC = ldap_bind_s(ld, NULL, NULL, LDAP_AUTH_NEGOTIATE);
                        if(LDAP_SUCCESS == ulRC)
                        {
                            // Setup the new values.
                            LPWSTR rgNewVals[] = {pwszNewDN, NULL};

                            /*
                            Remove the isDeleted attribute. This cannot be set 
                            to FALSE or the restore operation will not work.
                            */
                            LDAPModW modIsDeleted = { LDAP_MOD_DELETE, L"isDeleted", NULL };

                            /*
                            Set the new DN, in effect, moving the deleted 
                            object to where it resided before the deletion.
                            */
                            LDAPModW modDN = { LDAP_MOD_REPLACE, L"distinguishedName", rgNewVals };
                            
                            // Initialize the LDAPMod structure.
                            PLDAPModW ldapMods[] = 
                            {
                                &modIsDeleted,
                                &modDN,
                                NULL
                            };

                            /*
                            Use the LDAP_SERVER_SHOW_DELETED_OID control to 
                            modify deleted objects.
                            */
                            LDAPControlW showDeletedControl;
                            showDeletedControl.ldctl_oid = LDAP_SERVER_SHOW_DELETED_OID_W;
                            showDeletedControl.ldctl_value.bv_len = 0;
                            showDeletedControl.ldctl_value.bv_val = NULL;
                            showDeletedControl.ldctl_iscritical = TRUE;

                            // Initialzie the LDAPControl structure
                            PLDAPControlW ldapControls[] = { &showDeletedControl, NULL };

                            /*
                            Modify the specified attributes. This must performed 
                            in one step, which is why the LDAP APIs must be used 
                            to restore a deleted object.
                            */
                            ulRC = ldap_modify_ext_sW(ld, (PWCHAR)pwszDeletedDN, ldapMods, ldapControls, NULL);
                            if(LDAP_SUCCESS == ulRC)
                            {
                                hr = S_OK;
                            }
                            else if(LDAP_ALREADY_EXISTS == ulRC)
                            {
                                /*
                                An object already exists with the specified name 
                                in the specified target container. At this point, 
                                a new name must be selected.
                                */
                            }
                        }
                    }
                }

                if(LDAP_SUCCESS != ulRC)
                {
                    hr = ulRC;
                    
                    OutputDebugString(ldap_err2string(ulRC));
                }

                // Release the LDAP session.
                ldap_unbind(ld);
            }
        }
        else
        {
            /*
            If the end of the string is reached before the delimiter is found, just 
            end and fail.
            */
            hr = E_INVALIDARG;
        }
    
        delete pwszNewDN;
    }
    else
    {
        hr = E_OUTOFMEMORY;
    }

    return hr;
}
void CWE90_LDAP_Injection__w32_char_environment_18_bad()
{
    char * data;
    char dataBuffer[256] = "";
    data = dataBuffer;
    goto source;
source:
    {
        /* Append input from an environment variable to data */
        size_t dataLen = strlen(data);
        char * environment = GETENV(ENV_VARIABLE);
        /* If there is data in the environment variable */
        if (environment != NULL)
        {
            /* POTENTIAL FLAW: Read data from an environment variable */
            strncat(data+dataLen, environment, 256-dataLen-1);
        }
    }
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        char filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snprintf(filter, 256-1, "(cn=%s)", data);
        pLdapConnection = ldap_initA("localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sA(
                            pLdapConnection,
                            "base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}
Example #24
0
ldap_key_t * ldap_getuserkey(ldap_opt_t *l, const char * user) {
    ldap_key_t * k = (ldap_key_t *) calloc (1, sizeof(ldap_key_t));
    LDAPMessage *res, *e;
    char * filter;
    int i;
    char *attrs[] = {
      l->pub_key_attr,
      NULL
    };

    if ((!k) || (!l))
         return NULL;

    /* Am i still connected ? RETRY n times */
    /* XXX TODO: setup some conf value for retrying */
    if (!(l->flags & FLAG_CONNECTED))
        for (i = 0 ; i < 2 ; i++)
            if (ldap_connect(l) == 0)
                break;

    /* quick check for attempts to be evil */
    if ((strchr(user, '(') != NULL) || (strchr(user, ')') != NULL) ||
        (strchr(user, '*') != NULL) || (strchr(user, '\\') != NULL))
        return NULL;

    /* build  filter for LDAP request */
    REQUEST_USER(filter, user, l->filter);

    if ( ldap_search_st( l->ld,
        l->u_basedn,
        LDAP_SCOPE_SUBTREE,
        filter,
        attrs, 0, &l->s_timeout, &res ) != LDAP_SUCCESS) {
        
        ldap_perror(l->ld, "ldap_search_st()");

        free(filter);
        free(k);

        /* XXX error on search, timeout etc.. close ask for reconnect */
        ldap_close(l);

        return NULL;
    } 

    /* free */
    free(filter);

    /* check if any results */
    i = ldap_count_entries(l->ld,res);
    if (i <= 0) {
        ldap_msgfree(res);
        free(k);
        return NULL;
    }

    if (i > 1)
        debug("[LDAP] duplicate entries, using the FIRST entry returned");

    e = ldap_first_entry(l->ld, res);
    k->keys = ldap_get_values_len(l->ld, e, l->pub_key_attr);
    k->num = ldap_count_values_len(k->keys);

    ldap_msgfree(res);
    return k;
}