microsoft / cpprestsdk

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.
Other
7.96k stars 1.65k forks source link

TLS Handshake failed error #1649

Closed shyamaladevi17 closed 2 years ago

shyamaladevi17 commented 2 years ago

I'm trying out cpprestsdk for the first time and I followed some code samples to create a websocket client (Code below). I'm getting a "TLS Handshake Failed" error. The server uses a self signed certificate and so far all the searches said to turn off the certificate validation. But I've an c# client and it's able to connect to the server. Is there any other settings that needs to be enabled?

Note: both client and server are on the same machine.

C++ websocket_client* webSocketClient = new websocket_client(); utility::string_t url = "wss://" + hostName + ":" + ConvertToString(portNumber); webSocketClient->connect(url).wait(); } catch (const websocket_exception& e) {//TLS handshake failed caught here }

c# _wss = new ClientWebSocket(); Uri wsServerEndpoint = new Uri($"wss://Win2016-a:11000"); using (CancellationTokenSource tokenSource = new CancellationTokenSource(_STREAM_SERVER_CONNECT_TIMEOUT)) { _wss.ConnectAsync(wsServerEndpoint, tokenSource.Token).GetAwaiter().GetResult(); }

Thank you.

shyamaladevi17 commented 2 years ago

Looks like on Windows machine the SSL context is not able to load the certificates from root CA store. Fixed it by loading the certificate and assigning the same to ssl context. websocket_client_config config;
config.set_ssl_context_callback([this](boost::asio::ssl::context& ctx) {
// attach X509_STORE to boost ssl context HCERTSTORE hStore = CertOpenSystemStore(0, "ROOT"); if (hStore == NULL) { return; } m_RootCACertificateStore = X509_STORE_new(); PCCERT_CONTEXT pContext = NULL; while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != NULL) { // convert from DER to internal format X509* x509 = d2i_X509(NULL, (const unsigned char**)&pContext->pbCertEncoded, pContext->cbCertEncoded); if (x509 != NULL) { X509_STORE_add_cert(m_RootCACertificateStore, x509); X509_free(x509); } }

CertFreeCertificateContext(pContext);
CertCloseStore(hStore, 0);  
            SSL_CTX_set1_cert_store(ctx.native_handle(),m_RootCACertificateStore );
        });