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 disabledcert- Our own certificate; an mg_str. If NULL, then we don't authenticate ourselves to the other peerkey- 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 forcertandkeycould be the samename- Server name; an mg_str. If not empty, enable server name verification
NOTE: if both
caandcertare set, then two-way (mutual) TLS authentication is enabled, both sides authenticate each other. Usually, for one-way (server) TLS authentication, server connections set bothkeyandcert, whilst clients onlycaand/or possiblyname.
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_randomas RNG. Themg_randomfunction can be overridden by settingMG_ENABLE_CUSTOM_RANDOM=1and defining your ownmg_random()implementation.
Parameters:
c- Connection, for which TLS should be initializedopts- TLS initialization parameters
Return value: None
Usage example:
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);
Full examples: tutorials/http/http-server, tutorials/http/http-client, tutorials/mqtt/mqtt-client-aws-iot, tutorials/websocket/websocket-client Related APIs: mg_http_listen(), mg_http_connect(), mg_ws_connect(), mg_mqtt_connect() Notes: Call from the user-supplied event handler on MG_EV_ACCEPT for servers or MG_EV_CONNECT for clients, before application data is sent. Servers usually set cert and key. Clients usually set ca and name; name enables SNI and hostname verification.
NOTE: Certificate verification requires valid system time. Configure Mongoose with a system time according to your security needs.