Next: , Up: Advanced topics   [Contents][Index]

6.12.1 Virtual hosts and credentials

Often when operating with virtual hosts, one may not want to associate a particular certificate set to the credentials function early, before the virtual host is known. That can be achieved by calling gnutls_credentials_set within a handshake pre-hook for client hello. That message contains the peer’s intended hostname, and if read, and the appropriate credentials are set, gnutls will be able to continue in the handshake process. A brief usage example is shown below.

static int ext_hook_func(void *ctx, unsigned tls_id,
                         const unsigned char *data, unsigned size)
	if (tls_id == 0) { /* server name */
		/* figure the advertised name - the following hack
                 * relies on the fact that this extension only supports
                 * DNS names, and due to a protocol bug cannot be extended
                 * to support anything else. */
		if (name < 5) return 0;
		name = data+5;
		name_size = size-5;
	return 0;

static int
handshake_hook_func(gnutls_session_t session, unsigned int htype,
                    unsigned when, unsigned int incoming, const gnutls_datum_t *msg)
    int ret;

    assert(when == GNUTLS_HOOK_PRE);

    ret = gnutls_ext_raw_parse(NULL, ext_hook_func, msg,
    assert(ret >= 0);

    gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cred);

    return ret;

int main(void)

  gnutls_handshake_set_hook_function(server, GNUTLS_HANDSHAKE_CLIENT_HELLO,
                                     GNUTLS_HOOK_PRE, handshake_hook_func);
Function: void gnutls_handshake_set_hook_function (gnutls_session_t session, unsigned int htype, int when, gnutls_handshake_hook_func func)

session: is a gnutls_session_t type

htype: the gnutls_handshake_description_t of the message to hook at

when: GNUTLS_HOOK_ * depending on when the hook function should be called

func: is the function to be called

This function will set a callback to be called after or before the specified handshake message has been received or generated. This is a generalization of gnutls_handshake_set_post_client_hello_function() .

To call the hook function prior to the message being generated or processed use GNUTLS_HOOK_PRE as when parameter, GNUTLS_HOOK_POST to call after, and GNUTLS_HOOK_BOTH for both cases.

This callback must return 0 on success or a gnutls error code to terminate the handshake.

To hook at all handshake messages use an htype of GNUTLS_HANDSHAKE_ANY .

Warning: You should not use this function to terminate the handshake based on client input unless you know what you are doing. Before the handshake is finished there is no way to know if there is a man-in-the-middle attack being performed.

Next: , Up: Advanced topics   [Contents][Index]