WinHttp and TLS and WebSockets in C + Win32API

David Clarke (eicx.com) 0 Reputation points
2023-03-09T19:06:12.6+00:00

We are trying to add WebSocket communications to an existing program.

We are trying to connect to hardware that is waiting for an WebSocket connection on port 5001.

Hardware manufacturer has given us a sample program in Python to prove hardware is working - it is.

Python sample calls hardware after one SYN, one SYN ACK and one ACK Python sample sends a "Client Hello" works fine.

Trying to do the same thing with WinHttp.

1 - call WinHttpConnect - get session handle

2 - call WinHttpOpenRequest - get request handle

Note: WinHttpSetOption can be called with Session handle or a Request handle

We call it with WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET using a Request handle

3 - call WinHttpSetOption - send Request handle and WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET - It Returns True (success)

4 - call WinHttpSendRequest - send Request handle

Call to WinHttpSendRequest returns error:

ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED

QUESTION: Is there a way I could have told the request in advance that I already know the auth_cert? In python I simply add cert_path='comm.crt' to the APIWebSocketClient call.

Then I try:

Note: Using SessionHandle here as per - https://learn.microsoft.com/en-us/windows/win32/winhttp/option-flags

DWORD secure_protocols = %WINHTTP_FLAG_SECURE_PROTOCOL_ALL OR %WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3

Note: Using SessionHandle here as per - https://learn.microsoft.com/en-us/windows/win32/winhttp/option-flags

calling WinHttpSetOption(hSessionHandle, %WINHTTP_OPTION_SECURE_PROTOCOLS, secure_protocols, SIZEOF(secure_protocols))

Calling that results in an invalid memory error.

If we remove the above call to WinHttpSetOption and then call:

5 - WinHttpSetOption(hRequestHandle, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, 0,0)

6 - call WinHttpSendRequest(hRequestHandle, WINHTTP_NO_ADDITIONAL_HEADERS,0,0,0,0,0)

Results:

error - ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED

Could somebody enlighten me and show how to get the cert into the picure.

There are some cryptic discussions about looking through all the certs to find the one you want.

HOWEVER - There is no instruction as to what to do if you find one you want...

Thanks!

Windows development Windows API - Win32
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 12,731 Reputation points Microsoft External Staff
    2023-03-10T03:17:18.27+00:00

    As ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED said, you need to set the client certificate context using WINHTTP_OPTION_CLIENT_CERT_CONTEXT.

    And ReadCertFromFile (PFXImportCertStore) could be useful to you.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.