diff --git a/src/Tls/TlsMbedTLS.c b/src/Tls/TlsMbedTLS.c index 0536b96..a4249d1 100644 --- a/src/Tls/TlsMbedTLS.c +++ b/src/Tls/TlsMbedTLS.c @@ -35,6 +35,7 @@ #include #include +#include #include #include @@ -57,12 +58,70 @@ typedef struct MbedCookie { mbedtls_pk_context serverkey; } MbedCookie; +static bool +AddPEM(mbedtls_x509_crt *certs, char *path) +{ + size_t len; + if (!certs || !path) + { + return false; + } + + len = strlen(path); + if (len >= 4 && StrEquals(&path[len - 1 - 4], ".pem")) + { + /* Parse it as a file */ + if (mbedtls_x509_crt_parse_file(certs, path) == 0) + { + return true; + } + } + + /* Parse it as a directory if it is not a .PEM + * Note that this is non-recursive. */ + return mbedtls_x509_crt_parse_path(certs, path) == 0; +} +static bool +RegisterPEMs(mbedtls_x509_crt *certs) +{ + char *cafile; + if (!certs) + { + return false; + } + + /* Step 0: Load from CYTO_TLS_CA if present to overwrite */ + cafile = getenv("CYTO_TLS_CA"); + if (AddPEM(certs, cafile)) + { + return true; + } + + /* Step 1: Try /etc/ssl/certs */ + if (AddPEM(certs, "/etc/ssl/certs")) + { + return true; + } + /* Step 2: Try loading off Mozilla's certificates */ + if (AddPEM(certs, "/usr/share/ca-certificates/mozilla")) + { + return true; + } + + /* Step 3: Try loading from its root directly*/ + if (AddPEM(certs, "/usr/share/ca-certificates")) + { + return true; + } + + /* Step 4: Give up. */ + return false; +} + void * TlsInitClient(int fd, const char *serverName) { MbedCookie *cookie; - char *cafile; - char *seed; int err; if (!serverName) { @@ -94,12 +153,9 @@ TlsInitClient(int fd, const char *serverName) Log(LOG_ERR, "MbedTLS failure on client init: %d", err); goto error; } - /* Add a source of entropy if possible(using the CYTO_TLS_SEED env). - * Note that we ignore the error code. */ - seed = getenv("CYTO_TLS_SEED"); - mbedtls_entropy_update_seed_file(&cookie->entropy, seed); - /* TODO */ + /* TODO: Reconsider a source of additional entropy. */ + cookie->serverFD.fd = fd; err = mbedtls_ssl_config_defaults( @@ -117,13 +173,12 @@ TlsInitClient(int fd, const char *serverName) } /* Setup key verification */ - cafile = getenv("CYTO_TLS_CA"); - if ((err = mbedtls_x509_crt_parse_file(&cookie->cert, cafile)) != 0) + if (!RegisterPEMs(&cookie->cert)) { char message[256]; mbedtls_strerror(err, message, 255); Log(LOG_ERR, "MbedTLS failure on client certs: %s", message); - //goto error; + goto error; } mbedtls_ssl_conf_ca_chain(&cookie->conf, &cookie->cert, NULL); @@ -217,6 +272,8 @@ TlsInitServer(int fd, const char *crt, const char *key) goto error; } + + if ((err = mbedtls_pk_parse_keyfile(&cookie->serverkey, key, NULL, mbedtls_entropy_func, &cookie->ctrDrbg)) != 0) { char message[256];