Require calling mbedtls_ssl_set_hostname() for security

In a TLS client, when using certificate authentication, the client should
check that the certificate is valid for the server name that the client
expects. Otherwise, in most scenarios, a malicious server can impersonate
another server.

Normally, the application code should call mbedtls_ssl_set_hostname().
However, it's easy to forget. So raise an error if mandatory certificate
authentication is in effect and mbedtls_ssl_set_hostname() has not been
called. Raise the new error code
MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME, for easy
identification.

But don't raise the error if the backward compatibility option
MBEDTLS_SSL_CLI_ALLOW_WEAK_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME is
enabled.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 993c69e..a5e5b28 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -9835,6 +9835,12 @@
 {
     if (!mbedtls_ssl_has_set_hostname_been_called(ssl)) {
         MBEDTLS_SSL_DEBUG_MSG(1, ("Certificate verification without having set hostname"));
+#if !defined(MBEDTLS_SSL_CLI_ALLOW_WEAK_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME)
+        if (mbedtls_ssl_conf_get_endpoint(ssl->conf) == MBEDTLS_SSL_IS_CLIENT &&
+            ssl->conf->authmode == MBEDTLS_SSL_VERIFY_REQUIRED) {
+            return MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME;
+        }
+#endif
     }
 
     *hostname = mbedtls_ssl_get_hostname_pointer(ssl);