cpp-httplib icon indicating copy to clipboard operation
cpp-httplib copied to clipboard

Handy API for in-memory certificate loading

Open jimmy-park opened this issue 2 years ago • 2 comments

Currently, I'm embedding some certificates into my code to avoid packaging with cert files. I saw that curl has a good example of this, so I ended up writing something like this.

// In some header
inline constexpr char my_cert[] = {
    "-----BEGIN CERTIFICATE-----\n"
    // ...
    "-----END CERTIFICATE-----\n"
};

X509_STORE* create_ca_cert_store(const char* data, std::size_t size)
{
    BIO* mem = nullptr;
    STACK_OF(X509_INFO)* inf = nullptr;
    X509_STORE* cts = nullptr;

    [&] {
        mem = BIO_new_mem_buf(data, size);
        if (!mem)
            return;

        inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
        if (!inf)
            return;

        cts = X509_STORE_new();
        if (!cts)
            return;

        for (int first = 0, last = sk_X509_INFO_num(inf); first < last; ++first) {
            X509_INFO* itmp = sk_X509_INFO_value(inf, first);
            if (!itmp)
                continue;

            if (itmp->x509)
                X509_STORE_add_cert(cts, itmp->x509);

            if (itmp->crl)
                X509_STORE_add_crl(cts, itmp->crl);
        }
    }();

    if (inf)
        sk_X509_INFO_pop_free(inf, X509_INFO_free);

    if (mem)
        BIO_free_all(mem);

    return cts;
}

int main() {
    SSLClient client { "httpbin.org" };
    // It returns nullptr if creating cert store fails
    // but set_ca_cert_store() will check it
    auto* store = create_ca_cert_store(my_cert, sizeof(my_cert));
    client.set_ca_cert_store(store);
    // ...
}

I tested without default system certs and it works fine. But it would be nice if we had an SSLClient::create_ca_cert_store API for in-memory cert loading.

jimmy-park avatar Jan 19 '23 14:01 jimmy-park

@jimmy-park thanks for the suggestion.

I saw that curl has a good example of this

Where did you find it?

yhirose avatar Jan 21 '23 06:01 yhirose

@yhirose I linked it to the curl. Here it is https://curl.se/libcurl/c/cacertinmem.html

jimmy-park avatar Jan 21 '23 06:01 jimmy-park

I second @jimmy-park's request. This feature is useful e.g. to build standalone binaries.

607011 avatar Apr 20 '23 20:04 607011

@jimmy-park sorry for the late reply. Your suggestion looks reasonable to be added into cpp-httplib. Could you make a pull request with a unit test, and close this issue? Thanks!

yhirose avatar Jun 02 '23 07:06 yhirose

@yhirose Okay I'll try it. Actually I already did similar things in my repo 😄

jimmy-park avatar Jun 02 '23 07:06 jimmy-park