TLS / Security

struct mg_tls_opts

struct mg_tls_opts {
  struct mg_str ca;    // CA certificate; for both listeners and clients. PEM or DER
  struct mg_str cert;  // Certificate. PEM or DER
  struct mg_str key;   // Private key. PEM or DER
  struct mg_str name;  // If not empty, enable server name verification
};

TLS options structure:

  • ca - Certificate Authority, an mg_str. Used to verify the certificate that the other end sends to us. If NULL, then server authentication for clients and client authentication for servers are disabled
  • cert - Our own certificate; an mg_str. If NULL, then we don't authenticate ourselves to the other peer
  • key - Our own private key; an mg_str. Sometimes, a certificate and its key are bundled in a single PEM file, in which case the values for cert and key could be the same
  • name - Server name; an mg_str. If not empty, enable server name verification

NOTE: if both ca and cert are set, then two-way (mutual) TLS authentication is enabled, both sides authenticate each other. Usually, for one-way (server) TLS authentication, server connections set both key and cert, whilst clients only ca and/or possibly name.

For more information on developing TLS clients and servers, and how to load credentials, see the TLS tutorial

mg_tls_init()

void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *);

Initialise TLS on a given connection.

NOTE: The mbedTLS implementation uses mg_random as RNG. The mg_random function can be overridden by setting MG_ENABLE_CUSTOM_RANDOM=1 and defining your own mg_random() implementation.

Parameters:

  • c - Connection, for which TLS should be initialized
  • opts - TLS initialization parameters

Return value: None

Usage example:

// client event handler:
  if (ev == MG_EV_CONNECT) {
    struct mg_tls_opts opts = {.ca = mg_str(s_tls_ca)};
    mg_tls_init(c, &opts);

// server event handler:
  if (ev == MG_EV_ACCEPT) {
    struct mg_tls_opts opts = {.cert = mg_str(s_tls_cert),
                               .key = mg_str(s_tls_key)};
    mg_tls_init(c, &opts);

For more information on developing TLS clients and servers, see the TLS tutorial