Examples › Socket Examples
socket_ssl_verify_cert
Legacy: examples_socket/ssl_verify_cert/testprog.cpp · Modern: examples_modern/socket/ssl_verify_cert/modern.cpp
Modern equivalent of the client side certificate check. The client connects with gxSocket, starts TLS with gxSSL, prints the peer certificate's subject and issuer, and checks it with VerifyCert() against the host name. The result is a std::optional<std::string> error (empty when the certificate is good), and the TLS connection is closed by an RAII guard. With no arguments it checks a local test server twice: once with the test certificate as the CA (good) and once with an unrelated certificate as the CA (refused); with "HOST [PORT [CA_FILE]]" it checks a real server.
Windows Schannel builds (the default) cannot make keys or certificates: put modern_test_*.pem and modern_other_*.pem, made with openssl (CN localhost) or by a Linux run of this program, in the folder first.
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| gxString / UString | std::string, std::string_view | C++98 / C++17 | string_view looks at text without copying it. |
| gxSocket | keep gxSocket (C++ has no sockets); servers in std::jthread with std::stop_token and select() timeouts | C++20 | Stopping is a request, not a canceled thread blocked in accept(). |
| gxSSL | keep gxSSL; certificate checking on (SetCAList + RequireVerifyCert); RAII close | C++11 |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_socket/ssl_verify_cert/testprog.cpp 115 lines
#include "gxdlcode.h" #if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library #include <iostream> using namespace std; // Use unqualified names for Standard C++ library #else // Use the old iostream library by default #include <iostream.h> #endif // __USE_ANSI_CPP__ #include "gxssl.h" // Program's main thread of execution. // ----------------------------------------------------------- int main(int argc, char **argv) { int error_level = 0; if(argc < 2) { cout << "ERROR - You must supply an HTTPS hostname" << "\n"; return 1; } gxString hostname = argv[1]; int port_number = 443; gxSocket client; gxSSL openssl_client; hostname.DeleteBeforeIncluding("https://"); hostname.DeleteAfterLastIncluding("/"); // Send the hostname to the server (SNI) for virtual hosted sites openssl_client.SetHostName(hostname.c_str()); // We must supply a trusted CA list for client-side cert verification openssl_client.SetCAList("ca-bundle.crt"); if(client.InitSocketLibrary() == 0) { if(client.InitSocket(SOCK_STREAM, port_number, hostname.c_str()) < 0) { cout << "ERROR - Cannot open connection to " << hostname.c_str() << " TCP port " << port_number << "\n"; cout << client.SocketExceptionMessage() << "\n"; return 1; } } else { cout << "ERROR - Cannot init socket library" << "\n"; cout << client.SocketExceptionMessage() << "\n"; return 1; } if(client.Connect() < 0) { cout << "ERROR - Cannot connect to " << hostname.c_str() << " TCP port " << port_number << "\n"; cout << client.SocketExceptionMessage() << "\n"; return 1; } if(openssl_client.OpenSSLSocket(client.GetSocket()) != gxSSL_NO_ERROR) { cout << "ERROR - Cannot open SSL socket to " << hostname.c_str() << " TCP port " << port_number << "\n"; cout << openssl_client.SSLErrorMessage() << "\n"; client.Close(); return 1; } if(openssl_client.ConnectSSLSocket() != gxSSL_NO_ERROR) { cout << "ERROR - Cannot connect SSL socket to " << hostname.c_str() << " TCP port " << port_number << "\n"; cout << openssl_client.SSLErrorMessage() << "\n"; openssl_client.CloseSSLSocket(); client.Close(); return 1; } // 10/24/2026: Use the gxSSL cert functions so this example works with // both OpenSSL and the native Windows Schannel builds. gxString subject, issuer; if(openssl_client.GetPeerCertInfo(subject, issuer) != gxSSL_NO_ERROR) { cout << "ERROR - No certificate presented by " << hostname.c_str() << "\n"; cout << "\n"; openssl_client.CloseSSLSocket(); client.Close(); return 1; } cout << "\n"; cout << "Certificate Info:" << "\n"; cout << "Subject: " << subject.c_str() << "\n"; cout << "Issuer: " << issuer.c_str() << "\n"; cout << "\n"; long X509_return_code = 0; int rv = openssl_client.VerifyCert(hostname.c_str(), &X509_return_code); if(X509_return_code != 0) { cout << "ERROR - Cannot verify " << hostname.c_str() << " certificate" << "\n"; cout << gxSSL::CertVerifyErrorString(X509_return_code) << "\n"; error_level = 1; } if(rv != 0) { cout << "ERROR - Cert verify returned an error condition" << "\n"; cout << openssl_client.SSLErrorMessage() << "\n"; error_level = 1; } if(error_level == 0) { cout << "SSL cert for " << hostname.c_str() << " verify passed" << "\n"; cout << "\n"; } else { cout << "SSL cert for " << hostname.c_str() << " verify failed" << "\n"; cout << "\n"; } openssl_client.CloseSSLSocket(); client.Close(); return error_level; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/socket/ssl_verify_cert/modern.cpp 59 lines
#include <cstdlib> #include <iostream> #include <optional> #include <string> #include "../common/modern_tls.h" using namespace modern_net; std::optional<std::string> check_server(const std::string &host, int port, const std::string &ca) { gxSocket sock; if(sock.InitSocket(SOCK_STREAM, port, const_cast<char *>(host.c_str())) < 0 || sock.Connect() < 0) return std::string(sock.SocketExceptionMessage()); gxSSL tls; struct Close { gxSSL &t; ~Close() { t.CloseSSLSocket(); } } guard{tls}; tls.SetCAList(ca.c_str()); if(!tls.InitCTX()) return std::string(tls.SSLExceptionMessage()); if(tls.OpenSSLSocket(sock.GetSocket()) != gxSSL_NO_ERROR || tls.ConnectSSLSocket() != gxSSL_NO_ERROR) return std::string(tls.SSLExceptionMessage()); gxString subject, issuer; if(tls.GetPeerCertInfo(subject, issuer) == gxSSL_NO_ERROR) std::cout << " subject: " << subject.c_str() << "\n issuer: " << issuer.c_str() << "\n"; long code = 0; if(tls.VerifyCert(host.c_str(), &code) != gxSSL_NO_ERROR) return std::string("verify failed: ") + gxSSL::CertVerifyErrorString(code); return std::nullopt; // Good certificate } int main(int argc, char **argv) { SocketLibrary lib; if(argc > 1) { int port = argc > 2 ? std::atoi(argv[2]) : 443; std::string ca = argc > 3 ? argv[3] : "/etc/pki/tls/certs/ca-bundle.crt"; auto err = check_server(argv[1], port, ca); std::cout << (err ? "Certificate refused: " + *err : std::string("Certificate verified")) << "\n"; return err ? 1 : 0; } if(!make_test_cert("modern_test_key.pem", "modern_test_cert.pem")) return 1; TlsServer server("modern_test_cert.pem", "modern_test_key.pem", "HTTP/1.0 204 No Content\r\n\r\n"); int port = server.start(); if(port < 0) { std::cout << "TLS server: " << server.error() << "\n"; return 1; } std::cout << "With the test certificate as the CA:\n"; auto good = check_server("localhost", port, "modern_test_cert.pem"); std::cout << (good ? " refused: " + *good : std::string(" verified")) << "\n"; // A CA the server's certificate was not signed by if(!make_test_cert("modern_other_key.pem", "modern_other_cert.pem", "other")) return 1; std::cout << "With another certificate as the CA:\n"; auto bad = check_server("localhost", port, "modern_other_cert.pem"); std::cout << (bad ? " refused: " + *bad : std::string(" verified")) << "\n"; return (!good && bad) ? 0 : 1; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_modern/socket/common/modern_tls.h 82 lines
#ifndef MODERN_TLS_H #define MODERN_TLS_H #include <filesystem> #include <string> #include <thread> #include "gxssl.h" #include "modern_net.h" namespace modern_net { inline bool make_test_cert(const std::string &key, const std::string &cert, const char *cn = "localhost") { namespace fs = std::filesystem; if(fs::exists(key) && fs::exists(cert)) return true; gxSSL ssl; if(ssl.InitPRNG() != gxSSL_NO_ERROR) return false; if(ssl.MakeRSAPrivateKey(key.c_str(), 2048) != gxSSL_NO_ERROR) return false; fs::permissions(key, fs::perms::owner_read | fs::perms::owner_write, fs::perm_options::replace); gxCertIssuerInfo ci; ci.sn = 1; ci.days = 30; ci.C = "US"; ci.ST = "State"; ci.L = "City"; ci.O = "DataReel modern example"; ci.OU = "Test"; ci.CN = cn; return ssl.MakeCertReq(key.c_str(), ci, cert.c_str()) == gxSSL_NO_ERROR; } class TlsServer { public: TlsServer(std::string cert, std::string key, std::string response) : cert_(std::move(cert)), key_(std::move(key)), response_(std::move(response)) {} ~TlsServer() { worker_.request_stop(); if(worker_.joinable()) worker_.join(); } int start() { // Returns the port or -1 if(!gxSSL::InitSSLibrary()) return -1; if(!ctx_.InitCTX(cert_.c_str(), key_.c_str())) return -1; int port = listen_loopback(listener_); if(port > 0) worker_ = std::jthread([this](std::stop_token st) { run(st); }); return port; } const char *error() { return ctx_.SSLExceptionMessage(); } private: void run(std::stop_token st) { while(!st.stop_requested()) { if(listener_.ReadSelect(listener_.GetSocket(), 0, 100000) <= 0) continue; gxsSocketAddress sa{}; gxsSocket_t c = listener_.Accept(listener_.GetSocket(), &sa); if(c < 0) continue; { gxSSL conn(ctx_.GetCTX()); // Shares the context struct Release { // RAII, on every path gxSSL &s; ~Release() { s.CloseSSLSocket(); s.ReleaseCTX(); } // ~gxSSL() must not free the context } release{conn}; conn.SetHandshakeTimeout(5); if(conn.OpenSSLSocket(c) == gxSSL_NO_ERROR && conn.AcceptSSLSocket() == gxSSL_NO_ERROR) { std::string req(2048, '\0'); if(conn.RecvSSLSocket(req.data(), int(req.size()) - 1, 5, 0) > 0) conn.SendSSLSocket(response_.data(), int(response_.size())); } } listener_.Close(c); } } std::string cert_, key_, response_; gxSSL ctx_; gxSocket listener_; std::jthread worker_; }; } // namespace modern_net #endif // MODERN_TLS_H // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20 cmake --build build-modern --target socket_ssl_verify_cert ./build-modern/socket_ssl_verify_cert
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
With the test certificate as the CA: subject: /C=US/ST=State/L=City/O=DataReel modern example/OU=Test/CN=localhost issuer: /C=US/ST=State/L=City/O=DataReel modern example/OU=Test/CN=localhost verified With another certificate as the CA: subject: /C=US/ST=State/L=City/O=DataReel modern example/OU=Test/CN=localhost issuer: /C=US/ST=State/L=City/O=DataReel modern example/OU=Test/CN=localhost refused: verify failed: self-signed certificate