Click to See Complete Forum and Search --> : InternetOpenUrl() Invalid cert


Payne747
October 5th, 2009, 10:15 AM
Hi all,

Does anyone know how to prevent calls to InternetOpenUrl() from failing with error 12045 (ERROR_INTERNET_INVALID_CA)? I have the following code below:


HINTERNET IntOpen = ::InternetOpen(L"Sample", LOCAL_INTERNET_ACCESS, NULL, 0, 0);
HINTERNET handle = ::InternetOpenUrl(IntOpen, L"https://192.168.1.10/file.txt", NULL, NULL, INTERNET_FLAG_IGNORE_CERT_CN_INVALID, NULL);
if (handle == NULL) {
cout << "Error opening URL, " << GetLastError();
return 1;
}

char buf[1024];
DWORD dwRead = 0;
while (InternetReadFile(handle, buf, sizeof(buf), &dwRead) == TRUE) {
if (dwRead == 0)
break;
cout << buf;
}


This works OK on valid sites, but since my server has a self signed certificate, it fails with error code 12045. I know the INTERNET_FLAG_IGNORE_CERT_CN_INVALID is technically looking for hostname mismatches, and not invalid CA's.

Any help would be appreicated.

Thanks,

Payne747

Payne747
October 6th, 2009, 12:05 PM
For completeness - if anyone else comes across this, I managed to work around by using the dialog box option, and dropping InternetOpenUrl(), not perfect but gets results:


/* cip is char * containing ip
Also cheated and used ANSI version to save encoding char to UTF-16 */

HINTERNET hOpen = InternetOpen(L"User-Agent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL);
if (hOpen == NULL) {
std::cout << "Failed in InternetOpen()";
return 1;
}

/* Connect to port 80 */
HINTERNET hConnect = InternetConnectA(hOpen, cip, 80, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL);
if (hConnect == NULL) {
std::cout << "Failed in InternetConnect()";
return 1;
}

/* Prepare HTTPS request */
HINTERNET hReq = HttpOpenRequest(hConnect, L"GET", L"index.html", NULL, NULL, NULL, INTERNET_FLAG_SECURE, NULL);
if (hReq == NULL) {
std::cout << "Failed in HttpOpenRequest()";
return 1;
}

/* Send HTTPS request - lot can go wrong here! */
DWORD dwError;
while (!HttpSendRequest(hReq, NULL, NULL, NULL, 0)) {
/* Something went wrong, most likely invalid cert */
dwError = GetLastError();
if (dwError == ERROR_INTERNET_INVALID_CA) // Error code 12045
{
std::cout << "Invalid certificate detected\n";
// Return ERROR_SUCCESS regardless of clicking on OK or Cancel
if( InternetErrorDlg( GetDesktopWindow(),
hReq,
ERROR_INTERNET_INVALID_CA,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,
NULL) != ERROR_SUCCESS ) {
std::cout << "Certificate not accepted, unable to connect.\n";
return 1;
}
}
else {
std::cout << "Something went wrong, error code: " << dwError << ".\n";
return 1;
}
}

std::cout << "Request sent OK.\n";