简体   繁体   中英

InternetOpenUrl with self signed certificate

The following code is used to download files, but not working if the server has a self signed certificate:

DWORD errCode = 0;
HINTERNET intOpenHandle = InternetOpen("Snippet", LOCAL_INTERNET_ACCESS, NULL, 0, 0);
errCode = GetLastError();
if (intOpenHandle != NULL && errCode == ERROR_SUCCESS)
{
    HINTERNET urlOpenHandle = InternetOpenUrl(intOpenHandle, url, NULL, NULL, NULL, NULL);
    errCode = GetLastError();
    if (urlOpenHandle != NULL && errCode == ERROR_SUCCESS)
    {
        ...

Is there a way to modify this to work with self signed certificates, too?

It seems it is not possible with InternetOpenUrl() and InternetSetOptions() : The latter requires an open connection handle, not the session handle the former provides.
Therefore i had to use a bit longer version:

DWORD errCode = 0;
HINTERNET intOpenHandle = InternetOpen("Snippet", LOCAL_INTERNET_ACCESS, NULL, 0, 0);
if (intOpenHandle != NULL)
{
     HINTERNET httpRequest = HttpOpenRequest(intConnect, "GET", urlPath, NULL, NULL, NULL,
                                             INTERNET_FLAG_SECURE, 0);
     if (httpRequest != NULL)
     {
         DWORD dwFlags;
         DWORD dwBuffLen = sizeof(dwFlags);
         if (InternetQueryOption(httpRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, &dwBuffLen))
         {
             dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_WEAK_SIGNATURE |
                        SECURITY_FLAG_IGNORE_WRONG_USAGE;
             InternetSetOption(httpRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof(dwFlags));
         }
         if (HttpSendRequest(httpRequest, NULL, 0, NULL, 0))
         {
             ...

Here is the Delphi solution:

var
  Size: DWord;
...

//weaken security for local development
Size := SizeOf(DWORD);
if InternetQueryOption(Request, INTERNET_OPTION_SECURITY_FLAGS, @flags, Size) then
begin
  flags := flags or SECURITY_SET_MASK;
  InternetSetOption(Request, INTERNET_OPTION_SECURITY_FLAGS, @flags, Size);
end;

SECURITY_SET_MASK is defined as:

SECURITY_SET_MASK = SECURITY_FLAG_IGNORE_REVOCATION or 
SECURITY_FLAG_IGNORE_UNKNOWN_CA or
SECURITY_FLAG_IGNORE_CERT_CN_INVALID or
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID or
SECURITY_FLAG_IGNORE_WRONG_USAGE;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM