Boost TLS Server/Client Example

  boost, boost-asio, c++, ssl, tls1.2

I’ve been wanting to establish a secure connection between a client and server using Boost libraries. After following some guides about how an SSL connection is established, I tweaked an example that I’ve found to send a GET request to google.com:

client.cpp

// requires OpenSSL libraries!!
// sends a GET request to google.com and prints the response

#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>

namespace io = boost::asio;
namespace ip = io::ip;
using tcp = ip::tcp;
using error_code = boost::system::error_code;

namespace ssl = io::ssl;
using ssl_socket = ssl::stream<tcp::socket>;

int main(int argc, char* argv[])
{
    io::io_context io_context;
    ssl::context ssl_context(ssl::context::tls);

    ssl_socket socket(io_context, ssl_context);

    tcp::resolver resolver(io_context);
    auto endpoints = resolver.resolve("google.com", "443");
    try {
        std::cout << "attempting to connect to google.com..." << "n";
        io::connect(socket.next_layer(), endpoints);

        std::cout << "SSL handshake..." << "n";
        socket.handshake(ssl::stream_base::client);
    }
    catch (const boost::system::error_code e) {
        std::cerr << "error occured while connecting or during SSL handshake: " << e.message() << "n";
    }

    char request[] =
        "GET / HTTP/1.1n"
        "Host: www.google.comn"
        "Connection: closenn";

    std::cout << "sending GET request to google.com..." << "n";
    io::write(socket, io::buffer(request));

    std::cout << "awaiting response from google.com..." << "n";
    io::streambuf response;
    error_code ec;
    io::read(socket, response, ec);
    std::cout << std::istream(&response).rdbuf() << "n";

    return 0;
}

While this example does seem to work, I’ve read that I need to do additional steps such as "certificate verification" or "SSL version restriction". What does this code lack to be secure enough to be production-ready? How would the implementation of what’s missing would be implemented in Boost?

Source: Windows Questions C++

LEAVE A COMMENT