Error when trying to retrieve an ssl certificate

If you are referring to the HTTP response to the proxy CONNECT request, then presumably an error means the proxy is not actually connecting you to the upstream server, so you won’t be able to complete a TLS handshake with it.

If you start the TLS handshake anyway, the ClientHello message will be interpreted by the proxy, which will likely respond with an error, which the TLS client will fail to interpret as handshake messages. Hence the CLIENT ALERT: Fatal - Unexpected Message response.

Another issue with your sample code is that :gen_tcp.recv(tcp, 0, 5000) is not guaranteed to consume the entire response to the CONNECT request. One way to ensure the entire HTTP response is read is by using active: false, packet: : http_bin in the connect call, and then iterating over the :http_response, ::http_header and :http_eoh messages you’ll receive. Then you call :inet.setopts(tcp, packet: :raw), and if necessary read the request body (number of bytes indicated in the Content-Length header). Only then can you be actually sure that the TCP connection is ready for the handshake (provided the proxy returned a success response).