c++sslboosterror-handlingtls1.3

How to check TLS / SSL specific errors from boost::system::system_error


I have a TLS client that uses boost for the connect and handshake operations, and if they fail they will return a boost::system::system_error.

If possible, I want to check if the error code is related to one of the following cases:

I found the following error codes, however I can't find any that would be relevant to my case:

https://www.boost.org/doc/libs/1_87_0/boost/asio/error.hpp https://www.boost.org/doc/libs/master/libs/system/doc/html/system.html#ref_boostsystemerrc_hpp


Solution

  • Boost Asio reports the OpenSSL errors in the category asio::error::get_ssl_category(). As such you can "just" compare them. CAREFULLY. Never compare value() directly.

    Always use at least error_condition comparison operators. Prefer comparing error_condition wherever possible (read more here Testing for specific error conditions and Introduction).

    So, in reality when you want to check details:

    Live On Coliru

    #include <boost/asio/ssl.hpp>
    #include <iostream>
    namespace asio = boost::asio;
    using boost::system::error_code;
    
    void foo(error_code const& ec) {
        auto example = static_cast<asio::error::ssl_errors>( //
            ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNKNOWN_DIGEST_TYPE));
    
        // this uses the `make_error_code` overload for `asio::error::ssl_errors`
        if (auto expect = error_code (example)) {
            std::cout << "--\nExpect: " << expect.message() << std::endl;
        }
    
        if (ec == example) { // implict conversion to `error_code`
            std::cout << "Matched" << std::endl;
        } else {
            std::cout << "Mismatched: " << ec.message() << std::endl;
        }
    }
    
    int main() {
        OPENSSL_init(); // make sure strings already loaded
    
        foo(asio::error::operation_aborted);
        foo(error_code(ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_INVALID_SIGNED_DATA_TYPE),
                       asio::error::get_ssl_category()));
        foo(error_code(ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNKNOWN_DIGEST_TYPE),
                       asio::error::get_ssl_category()));
    
    }
    

    Printing

    --
    Expect: unknown digest type (PKCS7 routines, PKCS7 routines)
    Mismatched: Operation canceled
    --
    Expect: unknown digest type (PKCS7 routines, PKCS7 routines)
    Mismatched: invalid signed data type (PKCS7 routines, PKCS7 routines)
    --
    Expect: unknown digest type (PKCS7 routines, PKCS7 routines)
    Matched