diff --git a/lib/private/Security/TrustedDomainHelper.php b/lib/private/Security/TrustedDomainHelper.php
index 44e133746fd116122735290591dcbb4d04cf546d..cf4def63dd3e105239d67b044f6690690ca935c6 100644
--- a/lib/private/Security/TrustedDomainHelper.php
+++ b/lib/private/Security/TrustedDomainHelper.php
@@ -78,13 +78,16 @@ class TrustedDomainHelper {
 		if (preg_match(Request::REGEX_LOCALHOST, $domain) === 1) {
 			return true;
 		}
-
-		// match, allowing for * wildcards
+		// Reject misformed domains in any case
+		if (strpos($domain,'-') === 0 || strpos($domain,'..') !== false) {
+			return false;
+		}
+		// Match, allowing for * wildcards
 		foreach ($trustedList as $trusted) {
 			if (gettype($trusted) !== 'string') {
 				break;
 			}
-			$regex = '/^' . join('.*', array_map(function($v) { return preg_quote($v, '/'); }, explode('*', $trusted))) . '$/';
+			$regex = '/^' . join('[-\.a-zA-Z0-9]*', array_map(function($v) { return preg_quote($v, '/'); }, explode('*', $trusted))) . '$/';
 			if (preg_match($regex, $domain) || preg_match($regex, $domainWithPort)) {
  				return true;
  			}
diff --git a/tests/lib/Security/TrustedDomainHelperTest.php b/tests/lib/Security/TrustedDomainHelperTest.php
index 6c254dcaa79a82bcc31fd7b0f57efb3b0096b275..1beb7a667179533283bd78381686557b0c53f10b 100644
--- a/tests/lib/Security/TrustedDomainHelperTest.php
+++ b/tests/lib/Security/TrustedDomainHelperTest.php
@@ -102,6 +102,10 @@ class TrustedDomainHelperTest extends \Test\TestCase {
 			[$trustedHostTestList, 'abc.leadingwith.port:1234', false],
 			[$trustedHostTestList, 'trailingwith.port.abc:456', true],
 			[$trustedHostTestList, 'trailingwith.port.abc:123', false],
+			// bad hostname
+			[$trustedHostTestList, '-bad', false],
+			[$trustedHostTestList, '-bad.leading.host', false],
+			[$trustedHostTestList, 'bad..der.leading.host', false],
 		];
 	}
 }