C Collections

chttpserver · Section 3

chttpsvr_req_peer_cert_der

chttpsvr_req_peer_cert_der - give the DER encoding of the verified client certificate

C Collections (libccollections, -lccollections)

#include <ccollections/chttpserver.h>
 
const void *chttpsvr_req_peer_cert_der(const chttpsvr_req *req,
                                       size_t *len_out);

Returns the DER encoding of the leaf certificate that the TLS client
of the request presented and that verified against the
ca_bundle_path of the server.  You get it only when
chttpsvr_req_peer_cert_verified(3) reports true for req.
 
With it you can read any field of the certificate with the library
you like, such as d2i_X509() of OpenSSL, or compare the whole
certificate with a pinned one.  chttpsvr_req_peer_cert_sha256(3) and
chttpsvr_req_peer_cert_subject(3) give the two values that a handler
needs most often without a parse of its own.
 
The certificate is a property of the connection, so every request on
one keep-alive connection gets the same bytes, and a resumed TLS
session gets the certificate that the handshake which set up the
session verified.

req      The request handle.
len_out  Optional.  Receives the length of the encoding in bytes, or
         0 whenever the function returns NULL.

A pointer to the DER bytes, valid for the lifetime of the request.
Do not free them.
 
NULL in every case where chttpsvr_req_peer_cert_verified(3) reports
false (a plaintext connection, a server without a ca_bundle_path, a
client that presented no certificate, and a NULL req), and NULL as
well when an allocation fails.  Call chttpsvr_req_peer_cert_verified(3)
to tell these apart.

Like every other request accessor, call it only on the thread that
runs the handler or the middleware of req.

#include <ccollections/chttpserver.h>
#include <openssl/x509.h>
 
static void handler(chttpsvr_req *req, chttpsvr_resp *resp, void *ctx)
{
    (void)ctx;
    size_t len = 0;
    const unsigned char *der = chttpsvr_req_peer_cert_der(req, &len);
    if (!der) {
        /* No verified certificate, or an allocation failed. */
        chttpsvr_resp_set_status(resp, chttpsvr_req_peer_cert_verified(req)
                                           ? CHTTP_STATUS_INTERNAL_ERROR
                                           : CHTTP_STATUS_FORBIDDEN);
        return;
    }
    X509 *cert = d2i_X509(NULL, &der, (long)len);
    if (!cert) {
        chttpsvr_resp_set_status(resp, CHTTP_STATUS_INTERNAL_ERROR);
        return;
    }
    /* ... read the extensions that the policy needs ... */
    X509_free(cert);
    chttpsvr_resp_write_str(resp, "ok");
}

chttpsvr_req_peer_cert_verified(3), chttpsvr_req_peer_cert_sha256(3), chttpsvr_req_peer_cert_subject(3), CHTTP_TLS_DEFAULT(3), chttpsvr_start(3)